diff --git a/archive-js-api-version.sh b/archive-js-api-version.sh new file mode 100755 index 0000000000..2ec4fe3a07 --- /dev/null +++ b/archive-js-api-version.sh @@ -0,0 +1,15 @@ +#!/bin/sh + +VERSION=$1 +VERSION_FORMATTED=$(echo "$VERSION" | sed 's/\./-/g') + +cd src/data/markdown + +# create folder for archived version data +mkdir ./versioned-js-api/$VERSION + +# copy content of docs/javascript api to the version folder +cp -r ./docs/02\ javascript\ api/ ./versioned-js-api/$VERSION + +# replace internal links for javascript-api section (/javascript-api/ => /javascript-api/v0-XX/) +find ./versioned-js-api/$VERSION -type f -iname \*.md -exec sed -i "" -e "s/\/javascript-api\//\/javascript-api\/${VERSION_FORMATTED}\//g" {} \; diff --git a/gatsby-node.js b/gatsby-node.js index 5a6490dfb4..4f3dd6de20 100644 --- a/gatsby-node.js +++ b/gatsby-node.js @@ -24,6 +24,10 @@ const { getSlug, getTranslatedSlug, } = require('./src/utils/utils.node'); +const { + SUPPORTED_VERSIONS, + LATEST_VERSION, +} = require('./src/utils/versioning'); /* constants */ // auxilary flag to determine the environment (staging/prod) @@ -89,6 +93,69 @@ const getPageTranslations = ( return pageTranslations; }; +const getPageVersions = ( + getSidebar, + getJavascriptAPISidebar, + relativeDirectory, + name, + currentVersion = null, +) => { + const treeReducer = (subtree, currentNode) => { + if ( + !subtree || + typeof subtree.children === 'undefined' || + typeof subtree.children[currentNode] === 'undefined' + ) { + return null; + } + return subtree.children[currentNode]; + }; + + let filePath = unorderify( + stripDirectoryPath(relativeDirectory, 'javascript-api'), + // @TODO: maybe better use current version + // remove version prefix + ).slice(currentVersion ? currentVersion.length + 1 : 0); + + if (!currentVersion) { + filePath = unorderify( + stripDirectoryPath(relativeDirectory, 'docs'), + ).replace('javascript api/', ''); + } + + const pageVersions = {}; + + SUPPORTED_VERSIONS.forEach((version) => { + let versionedPath = [...filePath.split('/'), unorderify(name)].reduce( + treeReducer, + getJavascriptAPISidebar(version), + ); + + if (versionedPath && versionedPath.meta) { + versionedPath = versionedPath.meta; + } else { + versionedPath = null; + } + + if (versionedPath) { + pageVersions[version] = versionedPath; + } + }); + + // that's for latest only + const latestVersion = [...filePath.split('/'), unorderify(name)].reduce( + treeReducer, + // TODO: check if it's a correct sidebar node + getSidebar('javascript api'), + ); + + if (latestVersion && latestVersion.meta) { + pageVersions[LATEST_VERSION] = latestVersion.meta; + } + + return pageVersions; +}; + const generateTopLevelLinks = (topLevelLinks) => [ { label: 'guides', @@ -139,6 +206,10 @@ function generateSidebar({ nodes, type = 'docs' }) { pageSlug = '/'; } + if (type === 'javascript-api') { + pageSlug = `/javascript-api${pageSlug}`; + } + sidebarTreeBuilder.addNode( unorderify(stripDirectoryPath(relativeDirectory, type)), unorderify(name), @@ -183,6 +254,7 @@ function getSupplementaryPagesProps({ return childrenToList(getSidebar(section).children).map(({ name }) => { const path = `${section}/${name}`; const breadcrumbs = compose(buildBreadcrumbs, dedupePath)(path); + return { path: compose( removeEnPrefix, @@ -260,6 +332,7 @@ function getTopLevelPagesProps({ getSidebar, getGuidesSidebar, pathCollisionDetectorInstance, + getJavascriptAPISidebar, }) { // generating pages currently presented in templates/docs/ folder // for the exception of Cloud REST API @@ -322,6 +395,17 @@ function getTopLevelPagesProps({ }, }, ]) + .concat( + SUPPORTED_VERSIONS.map((version) => ({ + path: `/javascript-api/${version.replace(/\./g, '-')}/`, + component: Path.resolve(`./src/templates/docs/javascript-api.js`), + context: { + sidebarTree: getJavascriptAPISidebar(version), + navLinks: generateTopLevelLinks(topLevelLinks), + version, + }, + })), + ) .filter(Boolean); } @@ -330,6 +414,7 @@ function getDocPagesProps({ reporter, topLevelLinks, getSidebar, + getJavascriptAPISidebar, pathCollisionDetectorInstance, }) { // creating actual docs pages @@ -392,6 +477,17 @@ function getDocPagesProps({ const sidebarTree = getSidebar(docSection); + let pageVersions = null; + + if (slug.startsWith('javascript-api/')) { + pageVersions = getPageVersions( + getSidebar, + getJavascriptAPISidebar, + relativeDirectory, + name, + ); + } + return { path: slug, component: Path.resolve('./src/templates/doc-page.js'), @@ -400,6 +496,7 @@ function getDocPagesProps({ sidebarTree, breadcrumbs, navLinks: generateTopLevelLinks(topLevelLinks), + pageVersions, }, }; }) @@ -520,6 +617,118 @@ function getGuidesPagesProps({ .filter(Boolean); } +function getJsAPIVersionedPagesProps({ + nodesJsAPI, + reporter, + topLevelLinks, + pathCollisionDetectorInstance, + getJavascriptAPISidebar, + getSidebar, +}) { + // creating actual docs pages + return nodesJsAPI + .map(({ relativeDirectory, children: [remarkNode], name }) => { + const strippedDirectory = relativeDirectory.replace( + /^.*js-api\/(.*)$/, + '$1', + ); + // for debuggin purpose in case there are errors in md/html syntax + if (typeof remarkNode === 'undefined') { + reporter.warn( + `\nMarkup of a page is broken, unable to generate. Check the following file: \n\n + ${relativeDirectory}/${name}`, + ); + return false; + } + if (typeof remarkNode.frontmatter === 'undefined') { + reporter.warn( + `\nFrontmatter data is missing, unable to generate the page. Check the following file:\n\n ${relativeDirectory}/${name}`, + ); + return false; + } + const { + frontmatter, + frontmatter: { title, redirect, draft, slug: customSlug }, + } = remarkNode; + // if there is a value in redirect field, skip page creation + // OR there is draft flag and mode is prod + if ((draft === 'true' && isProduction) || redirect) { + return false; + } + const path = `javascript-api/${strippedDirectory}/${title.replace( + /\//g, + '-', + )}`; + + const pageVersion = SUPPORTED_VERSIONS.find((version) => + strippedDirectory.startsWith(version), + ); + + const slug = getSlug(path); + + const pageSlug = customSlug ? addTrailingSlash(customSlug) : slug; + + // path collision check + if ( + !pathCollisionDetectorInstance.add({ path: pageSlug, name }).isUnique() + ) { + // skip the page creation if there is already a page with identical url + return false; + } + + const sidebarTree = getJavascriptAPISidebar(pageVersion); + + const extendedRemarkNode = { + ...remarkNode, + frontmatter: { + ...frontmatter, + slug, + // injection of a link to an article in git repo + fileOrigin: encodeURI( + `https://github.com/k6io/docs/blob/master/src/data/${relativeDirectory}/${name}.md`, + ), + }, + }; + + const pathForBreadcrumbs = compose(dedupePath, unorderify)(path); + let breadcrumbs = buildBreadcrumbs(pathForBreadcrumbs, true); + breadcrumbs = breadcrumbs.map((item) => + SUPPORTED_VERSIONS.includes(item.name) + ? { + path: item.path, + name: 'Javascript API', + } + : item, + ); + + breadcrumbs = breadcrumbs.filter( + (item) => item.path !== '/' && item.path !== '/javascript-api/', + ); + + const pageVersions = getPageVersions( + getSidebar, + getJavascriptAPISidebar, + relativeDirectory, + name, + pageVersion, + ); + + return { + path: pageSlug || '/', + component: Path.resolve('./src/templates/doc-page.js'), + context: { + remarkNode: extendedRemarkNode, + sidebarTree, + breadcrumbs, + navLinks: generateTopLevelLinks(topLevelLinks), + version: pageVersion, + pageVersions, + }, + }; + }) + .filter(Boolean); +} + async function fetchDocPagesData(graphql) { const { data: { @@ -600,11 +809,53 @@ async function fetchGuidesPagesData(graphql) { return nodes; } +async function fetchJavascriptAPIPagesData(graphql) { + const { + data: { + allFile: { nodes }, + }, + } = await graphql( + ` + query guidesPagesQuery { + allFile( + filter: { + ext: { in: [".md"] } + relativeDirectory: { regex: "/versioned-js-api/" } + } + sort: { fields: absolutePath, order: ASC } + ) { + nodes { + name + relativeDirectory + children { + ... on Mdx { + body + frontmatter { + title + slug + head_title + excerpt + redirect + hideFromSidebar + draft + } + } + } + } + } + } + `, + ); + return nodes; +} + async function createDocPages({ nodes, nodesGuides, sidebar, guidesSidebar, + nodesJsAPI, + javascriptAPISidebar, actions, reporter, }) { @@ -617,6 +868,8 @@ async function createDocPages({ // local helper function that uses currying, expects one more arg const getGuidesSidebar = getChildSidebar(guidesSidebar); + const getJavascriptAPISidebar = getChildSidebar(javascriptAPISidebar); + // create data for rendering docs navigation const topLevelNames = Object.keys(sidebar.children); @@ -633,6 +886,7 @@ async function createDocPages({ topLevelLinks, pathCollisionDetectorInstance, getSidebar, + getJavascriptAPISidebar, }) .concat( getGuidesPagesProps({ @@ -642,11 +896,20 @@ async function createDocPages({ pathCollisionDetectorInstance, getGuidesSidebar, }), + getJsAPIVersionedPagesProps({ + nodesJsAPI, + reporter, + topLevelLinks, + pathCollisionDetectorInstance, + getJavascriptAPISidebar, + getSidebar, + }), getTopLevelPagesProps({ topLevelNames, topLevelLinks, getSidebar, getGuidesSidebar, + getJavascriptAPISidebar, pathCollisionDetectorInstance, }), getSupplementaryPagesProps({ @@ -654,6 +917,7 @@ async function createDocPages({ topLevelLinks, getSidebar, getGuidesSidebar, + getJavascriptAPISidebar, reporter, }), ) @@ -839,9 +1103,14 @@ const createRedirects = ({ actions }) => { exports.createPages = async (options) => { const pagesData = await fetchDocPagesData(options.graphql); const guidesData = await fetchGuidesPagesData(options.graphql); + const javascriptAPIData = await fetchJavascriptAPIPagesData(options.graphql); const sidebar = generateSidebar({ nodes: pagesData }); const guidesSidebar = generateSidebar({ nodes: guidesData, type: 'guides' }); + const javascriptAPISidebar = generateSidebar({ + nodes: javascriptAPIData, + type: 'javascript-api', + }); await createDocPages({ ...options, @@ -849,6 +1118,8 @@ exports.createPages = async (options) => { nodesGuides: guidesData, sidebar, guidesSidebar, + nodesJsAPI: javascriptAPIData, + javascriptAPISidebar, }); await createRedirects(options); }; diff --git a/package.json b/package.json index 447ef7060c..26f254ce1f 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,8 @@ "lint:fix": "eslint src/ --fix", "precheck:links": "gatsby build", "check:links": "concurrently --kill-others -s first \"gatsby serve --port 8000\" \"npm run check:blc\"", - "check:blc": "wait-on tcp:8000 && blc http://localhost:8000 -rof" + "check:blc": "wait-on tcp:8000 && blc http://localhost:8000 -rof", + "archive-version": "./archive-js-api-version.sh" }, "dependencies": { "@mdx-js/mdx": "^1.6.18", diff --git a/src/components/pages/doc-javascript-api/doc-javascript-api.module.scss b/src/components/pages/doc-javascript-api/doc-javascript-api.module.scss index f30862144f..aae377d52a 100644 --- a/src/components/pages/doc-javascript-api/doc-javascript-api.module.scss +++ b/src/components/pages/doc-javascript-api/doc-javascript-api.module.scss @@ -18,3 +18,11 @@ margin-top: 5px; } } + +.info { + margin-top: 165px; + + @include sm-down { + margin-top: 240px; + } +} diff --git a/src/components/shared/page-info/page-info.module.scss b/src/components/shared/page-info/page-info.module.scss index 387d6f433d..98c06c1e64 100644 --- a/src/components/shared/page-info/page-info.module.scss +++ b/src/components/shared/page-info/page-info.module.scss @@ -1,6 +1,6 @@ .container { margin-bottom: 47.5px; - margin-top: 105px; + margin-top: 115px; @include lg-down { margin-top: 160px; } diff --git a/src/components/shared/seo/seo.view.js b/src/components/shared/seo/seo.view.js index 35ee977c9b..7ea8a7fda0 100644 --- a/src/components/shared/seo/seo.view.js +++ b/src/components/shared/seo/seo.view.js @@ -4,11 +4,13 @@ import React from 'react'; import { Helmet } from 'react-helmet'; import { createMetaImagePath } from 'utils'; import { docs } from 'utils/urls'; +import { LATEST_VERSION } from 'utils/versioning'; export const SEO = ({ data: { title, description, image, slug } = {}, facebook, pageTranslations = null, + pageVersions = null, } = {}) => { const { site: { @@ -39,6 +41,13 @@ export const SEO = ({ const currentTitle = title || siteTitle; const currentDescription = description || siteDescription; const currentUrl = slug && slug !== '*' ? `${docs}/${slug}` : docs; + + let versionedCanonicalUrl = currentUrl; + // set canonical path to latest version URL if it's available + if (pageVersions && typeof pageVersions[LATEST_VERSION] !== 'undefined') { + versionedCanonicalUrl = `${docs}${pageVersions[LATEST_VERSION].path}`; + } + const currentImage = createMetaImagePath(image, siteUrl, siteImage); const hrefLangAttributes = { @@ -94,6 +103,9 @@ export const SEO = ({ + {/* Canonical links for versioned pages */} + + {/* SEO for localized pages */} {/* rel should be declared after href https://github.com/nfl/react-helmet/issues/279 */} {pageTranslations && pageTranslations.en !== undefined && ( diff --git a/src/components/shared/version-banner/index.js b/src/components/shared/version-banner/index.js new file mode 100644 index 0000000000..98b348d4c8 --- /dev/null +++ b/src/components/shared/version-banner/index.js @@ -0,0 +1 @@ +export { VersionBanner } from './version-banner'; diff --git a/src/components/shared/version-banner/version-banner.js b/src/components/shared/version-banner/version-banner.js new file mode 100644 index 0000000000..c2c8e670b9 --- /dev/null +++ b/src/components/shared/version-banner/version-banner.js @@ -0,0 +1,26 @@ +import { Link } from 'gatsby'; +import React from 'react'; +import { LATEST_VERSION } from 'utils/versioning'; + +import styles from './version-banner.module.scss'; + +export const VersionBanner = ({ version, versions }) => ( +
+
+
+ + ⚠️ This is archived documentation for {version}. + {typeof versions[LATEST_VERSION] !== 'undefined' && ( + + {' '} + Go to the{' '} + + latest version + + + )} + +
+
+
+); diff --git a/src/components/shared/version-banner/version-banner.module.scss b/src/components/shared/version-banner/version-banner.module.scss new file mode 100644 index 0000000000..9c0585d4e0 --- /dev/null +++ b/src/components/shared/version-banner/version-banner.module.scss @@ -0,0 +1,28 @@ +.wrapper { + position: absolute; + width: 100%; + top: 85px; + + @include sm-down { + display: flex; + align-items: center; + top: 160px; + } +} + +.inner { + display: flex; + align-items: center; + width: 100%; + background: $color-warning; + padding-top: 10px; + padding-bottom: 10px; + padding-left: 15px; + padding-right: 15px; + color: $color-tertiary; + border: 1px solid $color-warning-border; +} + +.message { + color: $color-primary; +} diff --git a/src/components/shared/version-switcher/index.js b/src/components/shared/version-switcher/index.js new file mode 100644 index 0000000000..3a27b59072 --- /dev/null +++ b/src/components/shared/version-switcher/index.js @@ -0,0 +1 @@ +export { VersionSwitcher } from './version-switcher.view'; diff --git a/src/components/shared/version-switcher/version-switcher.module.scss b/src/components/shared/version-switcher/version-switcher.module.scss new file mode 100644 index 0000000000..26a3a41d26 --- /dev/null +++ b/src/components/shared/version-switcher/version-switcher.module.scss @@ -0,0 +1,63 @@ +.wrapper { + display: flex; + flex-direction: column; + align-items: center; + position: relative; +} + +.current { + position: relative; + border: none; + outline: none; + background-color: transparent; + cursor: pointer; + color: $color-accent-primary; + font-size: 12px; + font-weight: 500; + + &::before { + position: absolute; + content: ''; + right: -16px; + top: 7px; + border-top: 4px solid $color-additional-1; + border-left: 6px solid transparent; + border-right: 6px solid transparent; + } + + &-open { + &::before { + transform: rotate(180deg); + } + } +} + +.menu { + z-index: 10; + position: absolute; + top: calc(100% + 5px); + left: -8px; + background-color: $color-additional-3; + + &-item { + border: none; + outline: none; + background-color: transparent; + + padding: 5px 15px; + color: $color-primary; + font-size: 12px; + line-height: 15.36px; + font-weight: 500; + cursor: pointer; + + @include hover-supported { + color: $color-accent-primary; + } + + &-active { + color: $color-accent-primary; + font-weight: 500; + } + } +} diff --git a/src/components/shared/version-switcher/version-switcher.view.js b/src/components/shared/version-switcher/version-switcher.view.js new file mode 100644 index 0000000000..aef3d2ba28 --- /dev/null +++ b/src/components/shared/version-switcher/version-switcher.view.js @@ -0,0 +1,55 @@ +import classNames from 'classnames'; +import { navigate } from 'gatsby'; +import React, { useState } from 'react'; +import { addTrailingSlash } from 'utils/utils.node'; +import { LATEST_VERSION } from 'utils/versioning'; + +import styles from './version-switcher.module.scss'; + +export const VersionSwitcher = ({ + currentVersion = LATEST_VERSION, + versions, + className, +}) => { + const [isOpen, setIsOpen] = useState(false); + + const availableVersions = Object.keys(versions).sort().reverse(); + + const handleVersionChange = (newVersion) => { + if (typeof window === 'undefined') { + return; + } + navigate(addTrailingSlash(versions[newVersion].path)); + }; + + return ( +
+ + {isOpen && ( +
+ {availableVersions + .filter((version) => version !== currentVersion) + .map((version) => ( + + ))} +
+ )} +
+ ); +}; diff --git a/src/components/templates/doc-page/doc-page.module.scss b/src/components/templates/doc-page/doc-page.module.scss index ccfc56f9c3..bbd048ee9f 100644 --- a/src/components/templates/doc-page/doc-page.module.scss +++ b/src/components/templates/doc-page/doc-page.module.scss @@ -16,6 +16,14 @@ width: 100%; padding: 0 20px; } + + &.versioned { + margin-top: 165px; + + @include sm-down { + margin-top: 240px; + } + } } .main-doc-content { diff --git a/src/data/markdown/docs/02 javascript api/05 k6-encoding.md b/src/data/markdown/docs/02 javascript api/05 k6-encoding.md index 3d2ef47b02..47cf1de0eb 100644 --- a/src/data/markdown/docs/02 javascript api/05 k6-encoding.md +++ b/src/data/markdown/docs/02 javascript api/05 k6-encoding.md @@ -7,5 +7,5 @@ encoding/decoding as defined by [RFC4648](https://tools.ietf.org/html/rfc4648). | Function | Description | | -------- | ----------- | -| [b64decode(input, [encoding])](/javascript-api/k6-encoding/b64decode-input-encoding) | Base64 decode a string. | -| [b64encode(input, [encoding])](/javascript-api/k6-encoding/b64encode-input-encoding) | Base64 encode a string. | +| [b64decode(input, [encoding], [format])](/javascript-api/k6-encoding/b64decode-input-encoding-format/) | Base64 decode a string. | +| [b64encode(input, [encoding])](/javascript-api/k6-encoding/b64encode-input-encoding/) | Base64 encode a string. | diff --git a/src/data/markdown/docs/02 javascript api/10 k6-ws.md b/src/data/markdown/docs/02 javascript api/10 k6-ws.md index 0d3e495fde..aceb46d439 100644 --- a/src/data/markdown/docs/02 javascript api/10 k6-ws.md +++ b/src/data/markdown/docs/02 javascript api/10 k6-ws.md @@ -13,9 +13,10 @@ The ws module provides a [WebSocket](https://en.wikipedia.org/wiki/WebSocket) cl | ----- | ----------- | | [Socket](/javascript-api/k6-ws/socket) | WebSocket client used to interact with a WS connection. | | [Socket.close()](/javascript-api/k6-ws/socket/socket-close) | Close the WebSocket connection. | -| [Socket.on(event, callback)](/javascript-api/k6-ws/socket/socket-on-event-callback) | Set up an event listener on the connection for any of the following events:
- open
- message
- ping
- pong
- close
- error. | +| [Socket.on(event, callback)](/javascript-api/k6-ws/socket/socket-on-event-callback) | Set up an event listener on the connection for any of the following events:
- open
- binaryMessage
- message
- ping
- pong
- close
- error. | | [Socket.ping()](/javascript-api/k6-ws/socket/socket-ping) | Send a ping. | -| [Socket.send(data)](/javascript-api/k6-ws/socket/socket-send-data) | Send data. | +| [Socket.send(data)](/javascript-api/k6-ws/socket/socket-send-data) | Send string data. | +| [Socket.sendBinary(data)](/javascript-api/k6-ws/socket/socket-sendbinary-data) | Send binary data. | | [Socket.setInterval(callback, interval)](/javascript-api/k6-ws/socket/socket-setinterval-callback-interval) | Call a function repeatedly at certain intervals, while the connection is open. | | [Socket.setTimeout(callback, period)](/javascript-api/k6-ws/socket/socket-settimeout-callback-delay) | Call a function with a delay, if the connection is open. | diff --git a/src/data/markdown/docs/02 javascript api/10 k6-ws/80 Socket.md b/src/data/markdown/docs/02 javascript api/10 k6-ws/80 Socket.md index b1c63a6bba..f9ff0999c2 100644 --- a/src/data/markdown/docs/02 javascript api/10 k6-ws/80 Socket.md +++ b/src/data/markdown/docs/02 javascript api/10 k6-ws/80 Socket.md @@ -8,9 +8,10 @@ excerpt: 'Socket is a WebSocket client to interact with a WebSocket connection.' | Method | Description | | ----------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Socket.close()](/javascript-api/k6-ws/socket/socket-close) | Close the WebSocket connection. | -| [Socket.on(event, callback)](/javascript-api/k6-ws/socket/socket-on-event-callback) | Set up an event listener on the connection for any of the following events:
- open
- message
- ping
- pong
- close
- error. | +| [Socket.on(event, callback)](/javascript-api/k6-ws/socket/socket-on-event-callback) | Set up an event listener on the connection for any of the following events:
- open
- binaryMessage
- message
- ping
- pong
- close
- error. | | [Socket.ping()](/javascript-api/k6-ws/socket/socket-ping) | Send a ping. | -| [Socket.send(data)](/javascript-api/k6-ws/socket/socket-send-data) | Send data. | +| [Socket.send(data)](/javascript-api/k6-ws/socket/socket-send-data) | Send string data. | +| [Socket.sendBinary(data)](/javascript-api/k6-ws/socket/socket-sendbinary-data) | Send binary data. | | [Socket.setInterval(callback, interval)](/javascript-api/k6-ws/socket/socket-setinterval-callback-interval) | Call a function repeatedly at certain intervals, while the connection is open. | | [Socket.setTimeout(callback, period)](/javascript-api/k6-ws/socket/socket-settimeout-callback-delay) | Call a function with a delay, if the connection is open. | diff --git a/src/data/markdown/docs/02 javascript api/10 k6-ws/80 Socket/Socket-send-data-.md b/src/data/markdown/docs/02 javascript api/10 k6-ws/80 Socket/Socket-send-data-.md index 252981a97a..3d423d31f9 100644 --- a/src/data/markdown/docs/02 javascript api/10 k6-ws/80 Socket/Socket-send-data-.md +++ b/src/data/markdown/docs/02 javascript api/10 k6-ws/80 Socket/Socket-send-data-.md @@ -1,9 +1,9 @@ --- title: 'Socket.send(data)' -excerpt: 'Send a data string through the connection. Binary data is not currently supported.' +excerpt: 'Send a data string through the connection.' --- -Send a data string through the connection. Binary data is not currently supported. +Send a data string through the connection. You can use `JSON.stringify` to convert a JSON or JavaScript values to a JSON string. | Parameter | Type | Description | @@ -29,3 +29,5 @@ export default function () { ``` + +- See also [Socket.sendBinary(data)](/javascript-api/k6-ws/socket/socket-sendbinary-data) diff --git a/src/data/markdown/docs/02 javascript api/10 k6-ws/80 Socket/Socket-sendBinary.md b/src/data/markdown/docs/02 javascript api/10 k6-ws/80 Socket/Socket-sendBinary.md new file mode 100644 index 0000000000..45c6106d9b --- /dev/null +++ b/src/data/markdown/docs/02 javascript api/10 k6-ws/80 Socket/Socket-sendBinary.md @@ -0,0 +1,37 @@ +--- +title: 'Socket.sendBinary(data)' +excerpt: 'Send binary data through the connection.' +--- + +Send binary data through the connection. + +| Parameter | Type | Description | +| --------- | ------ | ----------------- | +| data | ArrayBuffer | The data to send. | + +### Example + + + +```javascript +import ws from 'k6/ws'; + +const binFile = open('./file.pdf', 'b'); + +export default function () { + ws.connect('http://wshost/', function(socket) { + socket.on('open', function() { + socket.sendBinary(binFile); + }); + + socket.on('binaryMessage', function(msg) { + // msg is an ArrayBuffer, so we can wrap it in a typed array directly. + new Uint8Array(msg); + }); + }); +} +``` + + + +- See also [Socket.send(data)](/javascript-api/k6-ws/socket/socket-send-data) \ No newline at end of file diff --git a/src/data/markdown/versioned-js-api/v0.31/01 Init context.md b/src/data/markdown/versioned-js-api/v0.31/01 Init context.md new file mode 100644 index 0000000000..12099b1cd1 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/01 Init context.md @@ -0,0 +1,14 @@ +--- +title: "Init context" +excerpt: 'The init context (aka "init code") is code in the global context that has access to a few functions not accessible during main script execution.' +--- +The init context (aka "init code") is code in the global context that has +access to a few functions not accessible during main script execution (aka +"VU context" or "VU code"). For a more detailed description see +[Running k6](/getting-started/running-k6#section-the-init-context-and-the-default-function). + + + +| Function | Description | +| ----------------------------------------------------------------------------------- | --------------------- | +| [open( filePath, [mode] )](/javascript-api/v0-31/init-context/open-filepath-mode) | Opens a file and reads all the contents into memory. | diff --git a/src/data/markdown/versioned-js-api/v0.31/01 Init context/open.md b/src/data/markdown/versioned-js-api/v0.31/01 Init context/open.md new file mode 100644 index 0000000000..e1a0dde57e --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/01 Init context/open.md @@ -0,0 +1,113 @@ +--- +head_title: 'JavaScript API: open' +title: 'open( filePath, [mode] )' +description: 'Opens a file and reads all the contents into memory.' +excerpt: 'Opens a file and reads all the contents into memory.' +--- + +Opens a file, reading all its contents into memory for use in the script. + +> #### Use [SharedArray](/javascript-api/v0-31/k6-data/sharedarray/) for CSV and JSON files +> `open()` often consumes a large amount of memory because every VU keeps a separate copy of the file in memory. +> To reduce the memory consumption, we strongly advise the usage of [SharedArray](/javascript-api/v0-31/k6-data/sharedarray/) for CSV, JSON and other files intended for script parametrization. + +
+ +#### Function only available in "init context" + +This is a function that can only be called from the init context (aka **init code**), code in the global context that is, outside of the main export default function { ... }. + +By restricting it to the init context, we can easily determine what local files are needed to run the test and thus what we need to bundle up when distributing the test to multiple nodes in a clustered/distributed test. + +See example further down on this page. For more in-depth description see [Running k6](/getting-started/running-k6). + +
+ +| Parameter | Type | Description | +| --------- | ------ | ------------------ | +| filePath | string | The path to the file, absolute or relative, that will be read into memory. The file will only be loaded once, even when running with several VUs. | +| mode | string | By default the contents of the file is read as text, but if you specify `b` the file will be read as binary data instead. | + +### Returns + +| Type | Description | +| -------------- | ----------------------| +| string / Array | The contents of the file, returned as string or array of numbers (if `b` was specified as the mode). | + + + +```json +[ + { + "username": "user1", + "password": "password1" + }, + { + "username": "user2", + "password": "password2" + }, + { + "username": "user3", + "password": "password3" + } +] +``` + + + + + +```javascript +import { SharedArray } from "k6/data"; +import { sleep } from "k6"; + +var data = new SharedArray("users", function () { + // here you can open files, and then do additional processing or generate the array with data dynamically + var f = JSON.parse(open("./users.json")); + return f; // f must be an array[] +}); + +export default () => { + var randomUser = data[Math.floor(Math.random() * data.length)]; + console.log(`${randomUser.username}, ${randomUser.password}`); + sleep(3); +}; +``` + + + + + +```javascript +import { sleep } from 'k6'; + +const users = JSON.parse(open('./users.json')); // consider using SharedArray for large files + +export default function () { + let user = users[__VU - 1]; + console.log(`${user.username}, ${user.password}`); + sleep(3); +} +``` + + + + + +```javascript +import http from 'k6/http'; +import { sleep } from 'k6'; + +let binFile = open('/path/to/file.bin', 'b'); + +export default function () { + var data = { + field: 'this is a standard form field', + file: http.file(binFile, 'test.bin'), + }; + var res = http.post('https://example.com/upload', data); + sleep(3); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/02 k6.md b/src/data/markdown/versioned-js-api/v0.31/02 k6.md new file mode 100644 index 0000000000..4d291cd0ba --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/02 k6.md @@ -0,0 +1,14 @@ +--- +title: 'k6' +excerpt: 'The k6 module contains k6-specific functionality.' +--- + +The k6 module contains k6-specific functionality. + +| Function | Description | +| ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | +| [check(val, sets, [tags])](/javascript-api/v0-31/k6/check-val-sets-tags) | Runs one or more checks on a value and generates a pass/fail result but does not throw errors or otherwise interrupt execution upon failure. | +| [fail([err])](/javascript-api/v0-31/k6/fail-err) | Throws an error, failing and aborting the current VU script iteration immediately. | +| [group(name, fn)](/javascript-api/v0-31/k6/group-name-fn) | Runs code inside a group. Used to organize results in a test. | +| [randomSeed(int)](/javascript-api/v0-31/k6/randomseed-int) | Set seed to get a reproducible pseudo-random number using `Math.random`. | +| [sleep(t)](/javascript-api/v0-31/k6/sleep-t) | Suspends VU execution for the specified duration. | diff --git a/src/data/markdown/versioned-js-api/v0.31/02 k6/check- val- sets- -tags- -.md b/src/data/markdown/versioned-js-api/v0.31/02 k6/check- val- sets- -tags- -.md new file mode 100644 index 0000000000..6708c62745 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/02 k6/check- val- sets- -tags- -.md @@ -0,0 +1,46 @@ +--- +title: 'check( val, sets, [tags] )' +description: 'Runs one or more checks on a value and generates a pass/fail result but does not throw errors or otherwise interrupt execution upon failure.' +excerpt: 'Runs one or more checks on a value and generates a pass/fail result but does not throw errors or otherwise interrupt execution upon failure.' +--- + +Run checks on a value. A check is a test condition that can give a truthy or +falsy result. The `sets` parameter contains one or more checks, and the `check()` +function will return `false` if any of them fail. + +Note that checks are not _asserts_ in their traditional sense - a failed assertion +will throw an error, while a check will always return with a pass or a failure. +Failure conditions can then instead be controlled by thresholds, for more power and flexibility. + +| Parameter | Type | Description | +| --------------- | ------ | ---------------------------------------- | +| val | any | Value to test. | +| sets | object | Tests (checks) to run on the value. | +| tags (optional) | object | Extra tags to attach to metrics emitted. | + +### Returns + +| Type | Description | +| ------- | ------------------------------------------------------- | +| boolean | `true` if all checks have succeeded, `false` otherwise. | + +### Example + +Using `check()` to verify that an HTTP response code was 200 and that body was 1234 bytes: + + + +```javascript +import http from 'k6/http'; +import { check } from 'k6'; + +export default function () { + let res = http.get('http://httpbin.org'); + check(res, { + 'response code was 200': (res) => res.status == 200, + 'body size was 1234 bytes': (res) => res.body.length == 1234, + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/02 k6/fail- -err- -.md b/src/data/markdown/versioned-js-api/v0.31/02 k6/fail- -err- -.md new file mode 100644 index 0000000000..4d453bda16 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/02 k6/fail- -err- -.md @@ -0,0 +1,38 @@ +--- +title: 'fail( [err] )' +description: 'Throws an error, failing and aborting the current VU script iteration immediately.' +excerpt: 'Throws an error, failing and aborting the current VU script iteration immediately.' +--- + +Immediately throw an error, aborting the current script iteration. + +`fail()` is a simple convenience wrapper on top of JavaScript's `throw()`, +because the latter cannot be used as `[expr] || throw`, which is a convenient way to write k6 test code. + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------ | +| err (optional) | string | Error message that gets printed to stderr. | + +### Example + +Aborting the current script iteration if a check fails: + + + +```javascript +import http from 'k6/http'; +import { check, fail } from 'k6'; + +export default function () { + let res = http.get('https://k6.io'); + if ( + !check(res, { + 'status code MUST be 200': (res) => res.status == 200, + }) + ) { + fail('status code was *not* 200'); + } +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/02 k6/group- name- fn -.md b/src/data/markdown/versioned-js-api/v0.31/02 k6/group- name- fn -.md new file mode 100644 index 0000000000..40764e3091 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/02 k6/group- name- fn -.md @@ -0,0 +1,55 @@ +--- +title: 'group( name, fn )' +description: 'Runs code inside a group. Used to organize results in a test.' +excerpt: 'Runs code inside a group. Used to organize results in a test.' +--- + +Run code inside a group. Groups are used to organize results in a test. + +| Parameter | Type | Description | +| --------- | -------- | ------------------------------------------------------ | +| name | string | Name of the group. | +| fn | function | Group body - code to be executed in the group context. | + +### Returns + +| Type | Description | +| ---- | ------------------------- | +| any | The return value of _fn_. | + +### Example + + + +```javascript +import { group } from 'k6'; + +export default function () { + + group('visit product listing page', function () { + // ... + }); + group('add several products to the shopping cart', function () { + // ... + }); + group('visit login page', function () { + // ... + }); + group('authenticate', function () { + // ... + }); + group('checkout process', function () { + // ... + }); + +} +} +``` + + + +The above code will present the results separately depending on the group execution. + +Learn more on [Groups and Tags](/using-k6/tags-and-groups). + + diff --git a/src/data/markdown/versioned-js-api/v0.31/02 k6/images/groups.png b/src/data/markdown/versioned-js-api/v0.31/02 k6/images/groups.png new file mode 100644 index 0000000000..4135d30379 Binary files /dev/null and b/src/data/markdown/versioned-js-api/v0.31/02 k6/images/groups.png differ diff --git a/src/data/markdown/versioned-js-api/v0.31/02 k6/random-seed.md b/src/data/markdown/versioned-js-api/v0.31/02 k6/random-seed.md new file mode 100644 index 0000000000..7b543ddd3b --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/02 k6/random-seed.md @@ -0,0 +1,34 @@ +--- +title: 'randomSeed( int )' +description: 'Set seed to get a reproducible pseudo-random number using `Math.random`.' +excerpt: 'Set seed to get a reproducible pseudo-random number using `Math.random`.' +--- + +Set seed to get a reproducible pseudo-random number using `Math.random`. + +| Parameter | Type | Description | +| --------- | ------- | --------------- | +| int | integer | The seed value. | + +### Example + +Use `randomSeed` to get the same random number in all the iterations. + + + +```javascript +import { randomSeed } from 'k6'; + +export const options = { + vus: 10, + duration: '5s', +}; + +export default function () { + randomSeed(123456789); + let rnd = Math.random(); + console.log(rnd); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/02 k6/sleep- t -.md b/src/data/markdown/versioned-js-api/v0.31/02 k6/sleep- t -.md new file mode 100644 index 0000000000..970ce3954e --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/02 k6/sleep- t -.md @@ -0,0 +1,48 @@ +--- +title: 'sleep( t )' +description: 'Suspends VU execution for the specified duration.' +excerpt: 'Suspends VU execution for the specified duration.' +--- + +Suspend VU execution for the specified duration. + +| Parameter | Type | Description | +| --------- | ------ | --------------------- | +| t | number | Duration, in seconds. | + +### Examples + +Fetching two different pages with a 0-30 second random sleep in between: + + + +```javascript +import { sleep } from 'k6'; +import http from 'k6/http'; + +export default function () { + http.get('https://k6.io'); + sleep(Math.random() * 30); + http.get('https://k6.io/features'); +} +``` + + + +Using the [k6-utils](https://jslib.k6.io/k6-utils/) library to specify a range between a minimum and maximum: + + + +```javascript +import { sleep } from 'k6'; +import http from 'k6/http'; +import { randomIntBetween } from "https://jslib.k6.io/k6-utils/1.1.0/index.js"; + +export default function () { + http.get('https://k6.io'); + sleep(randomIntBetween(20, 30)); + http.get('https://k6.io/features'); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto.md new file mode 100644 index 0000000000..eb0c686512 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto.md @@ -0,0 +1,26 @@ +--- +title: "k6/crypto" +excerpt: "The k6/crypto module provides common hashing functionality available in the GoLang crypto." +--- +The k6/crypto module provides common hashing functionality available in the GoLang [crypto](https://golang.org/pkg/crypto/) package. + +| Function | Description | +| -------- | ----------- | +| [createHash(algorithm)](/javascript-api/v0-31/k6-crypto/createhash-algorithm) | Create a Hasher object, allowing the user to add data to hash multiple times, and extract hash digests along the way. | +| [createHMAC(algorithm, secret)](/javascript-api/v0-31/k6-crypto/createhmac-algorithm-secret) | Create an HMAC hashing object, allowing the user to add data to hash multiple times, and extract hash digests along the way. | +| [hmac(algorithm, secret, data, outputEncoding)](/javascript-api/v0-31/k6-crypto/hmac-algorithm-secret-data-outputencoding) | Use HMAC to sign an input string. | +| [md4(input, outputEncoding)](/javascript-api/v0-31/k6-crypto/md4-input-outputencoding) | Use MD4 to hash an input string. | +| [md5(input, outputEncoding)](/javascript-api/v0-31/k6-crypto/md5-input-outputencoding) | Use MD5 to hash an input string. | +| [randomBytes(int)](/javascript-api/v0-31/k6-crypto/randombytes-int) | Return an array with a number of cryptographically random bytes. | +| [ripemd160(input, outputEncoding)](/javascript-api/v0-31/k6-crypto/ripemd160-input-outputencoding) | Use RIPEMD-160 to hash an input string. | +| [sha1(input, outputEncoding)](/javascript-api/v0-31/k6-crypto/sha1-input-outputencoding) | Use SHA-1 to hash an input string. | +| [sha256(input, outputEncoding)](/javascript-api/v0-31/k6-crypto/sha256-input-outputencoding) | Use SHA-256 to hash an input string. | +| [sha384(input, outputEncoding)](/javascript-api/v0-31/k6-crypto/sha384-input-outputencoding) | Use SHA-384 to hash an input string. | +| [sha512(input, outputEncoding)](/javascript-api/v0-31/k6-crypto/sha512-input-outputencoding) | Use SHA-512 to hash an input string. | +| [sha512_224(input, outputEncoding)](/javascript-api/v0-31/k6-crypto/sha512_224-input-outputencoding) | Use SHA-512/224 to hash an input string. | +| [sha512_256(input, outputEncoding)](/javascript-api/v0-31/k6-crypto/sha512_256-input-outputencoding) | Use SHA-512/256 to hash an input string. | + + +| Class | Description | +| -------- | ----------- | +| [Hasher](/javascript-api/v0-31/k6-crypto/hasher) | Object returned by [crypto.createHash()](/javascript-api/v0-31/k6-crypto/createhash-algorithm). It allows adding more data to be hashed and to extract digests along the way. | diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/01-createHash- algorithm -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/01-createHash- algorithm -.md new file mode 100644 index 0000000000..498e72110d --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/01-createHash- algorithm -.md @@ -0,0 +1,42 @@ +--- +title: 'createHash( algorithm )' +description: 'Create a Hasher object, allowing the user to add data to hash multiple times, and extract hash digests along the way.' +excerpt: 'Create a Hasher object, allowing the user to add data to hash multiple times, and extract hash digests along the way.' +--- + +Creates a hashing object that can then be fed with data repeatedly, and from which you can extract a hash digest whenever you want. + +| Parameter | Type | Description | +| --------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| algorithm | string | The name of the hashing algorithm you want to use. Can be any one of "md4", "md5", "sha1", "sha256", "sha384", "sha512", "sha512_224", "sha512_256", "ripemd160". | + +### Returns + +| Type | Description | +| ------ | ---------------------------------------------------- | +| object | A [Hasher](/javascript-api/v0-31/k6-crypto/hasher) object. | + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + console.log(crypto.sha256('hello world!', 'hex')); + let hasher = crypto.createHash('sha256'); + hasher.update('hello '); + hasher.update('world!'); + console.log(hasher.digest('hex')); +} +``` + + + +The above script should result in the following being printed during execution: + +```bash +INFO[0000] 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9 +INFO[0000] 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9 +``` diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/02-createHMAC- algorithm- secret -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/02-createHMAC- algorithm- secret -.md new file mode 100644 index 0000000000..b1b77c4f5e --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/02-createHMAC- algorithm- secret -.md @@ -0,0 +1,43 @@ +--- +title: 'createHMAC( algorithm, secret )' +description: 'Create an HMAC hashing object, allowing the user to add data to hash multiple times, and extract hash digests along the way.' +excerpt: 'Create an HMAC hashing object, allowing the user to add data to hash multiple times, and extract hash digests along the way.' +--- + +Creates a HMAC hashing object that can then be fed with data repeatedly, and from which you can extract a signed hash digest whenever you want. + +| Parameter | Type | Description | +| --------- | :----: | :---------------------------------------------------------------------------------------------------------------------------------- | +| algorithm | string | The hashing algorithm to use. One of `md4`, `md5`, `sha1`, `sha256`, `sha384`, `sha512`, `sha512_224`, `sha512_256` or `ripemd160`. | +| secret | string / ArrayBuffer (≥ v0.31.0) | A shared secret used to sign the data. | + +### Returns + +| Type | Description | +| ------ | :--------------------------------------------------- | +| object | A [Hasher](/javascript-api/v0-31/k6-crypto/hasher) object. | + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + console.log(crypto.hmac('sha256', 'a secret', 'my data', 'hex')); + let hasher = crypto.createHMAC('sha256', 'a secret'); + hasher.update('my '); + hasher.update('data'); + console.log(hasher.digest('hex')); +} +``` + + + +The above script should result in the following being printed during execution: + +```bash +INFO[0000] 82f669c8fde13aef6d6977257588dc4953dfac505428f8fd6b52e19cd96d7ea5 +INFO[0000] 82f669c8fde13aef6d6977257588dc4953dfac505428f8fd6b52e19cd96d7ea5 +``` diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/03-hmac- algorithm- secret- data- outputEncoding -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/03-hmac- algorithm- secret- data- outputEncoding -.md new file mode 100644 index 0000000000..b7b4147a5f --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/03-hmac- algorithm- secret- data- outputEncoding -.md @@ -0,0 +1,50 @@ +--- +title: 'hmac( algorithm, secret, data, outputEncoding )' +description: 'Use HMAC to sign input data.' +excerpt: 'Use HMAC to sign input data.' +--- + +Use [HMAC](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code) to sign a piece of data using a shared secret. + +| Parameter | Type | Description | +| -------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------- | +| algorithm | string | The hashing algorithm to use. One of `md4`, `md5`, `sha1`, `sha256`, `sha384`, `sha512`, `sha512_224`, `sha512_256` or `ripemd160`. | +| secret | string / ArrayBuffer (≥ v0.31.0) | A shared secret used to sign the data. | +| data | string / ArrayBuffer (≥ v0.31.0) | The data to sign. | +| outputEncoding | string | Describes the type of encoding to use for the hash value. Can be "base64", "base64url", "base64rawurl", "hex" or "binary". | + +### Returns + +| Type | Description | +| -------------- | ----------- | +| string / Array | The hash digest as string (for "base64", "base64url", "base64rawurl", "hex" `outputEncoding`) or raw array of integers (for "binary" `outputEncoding`). | + + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + let hash = crypto.hmac('sha256', 'mysecret', 'hello world!', 'hex'); + console.log(hash); + let binArray = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]; + hash = crypto.hmac('sha256', 'mysecret', new Uint8Array(binArray).buffer, 'hex'); + console.log(hash); +} +``` + + + +The above script should result in the following being printed during execution: + + + +```bash +INFO[0000] 893a72d8cab129e5ba85aea4599fd53f59bfe652cff4098a3780313228d8c20f +INFO[0000] 893a72d8cab129e5ba85aea4599fd53f59bfe652cff4098a3780313228d8c20f +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/04-md4- input- outputEncoding -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/04-md4- input- outputEncoding -.md new file mode 100644 index 0000000000..b012b93677 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/04-md4- input- outputEncoding -.md @@ -0,0 +1,43 @@ +--- +title: 'md4( input, outputEncoding )' +description: 'Use MD4 to hash input data.' +excerpt: 'Use MD4 to hash input data.' +--- + +Use [md4](https://pkg.go.dev/golang.org/x/crypto/md4) to hash input data. + +| Parameter | Type | Description | +| -------------- | -------------------- | --------------------------------------------------| +| input | string / ArrayBuffer (≥ v0.31.0) | The input string or `ArrayBuffer` object to hash. | +| outputEncoding | string | Describes the type of encoding to use for the hash value. Can be "base64", "base64url", "base64rawurl", "hex" or "binary". | + +### Returns + +| Type | Description | +| -------------- | ----------- | +| string / Array | The hash digest as string (for "base64", "base64url", "base64rawurl", "hex" `outputEncoding`) or raw array of integers (for "binary" `outputEncoding`). | + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + let hash = crypto.md4('hello world!', 'hex'); + console.log(hash); + let binArray = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]; + hash = crypto.md4(new Uint8Array(binArray).buffer, 'hex'); + console.log(hash); +} +``` + + + +The above script should result in the following being printed during execution: + +```bash +INFO[0000] 3363b72840acd5f49f922fef598ee85d +INFO[0000] 3363b72840acd5f49f922fef598ee85d +``` diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/05-md5- input- outputEncoding -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/05-md5- input- outputEncoding -.md new file mode 100644 index 0000000000..3277bad62c --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/05-md5- input- outputEncoding -.md @@ -0,0 +1,43 @@ +--- +title: 'md5( input, outputEncoding )' +description: 'Use MD5 to hash input data.' +excerpt: 'Use MD5 to hash input data.' +--- + +Use [md5](https://golang.org/pkg/crypto/md5/) to hash input data. + +| Parameter | Type | Description | +| -------------- | -------------------- | --------------------------------------------------| +| input | string / ArrayBuffer (≥ v0.31.0) | The input string or `ArrayBuffer` object to hash. | +| outputEncoding | string | Describes the type of encoding to use for the hash value. Can be "base64", "base64url", "base64rawurl", "hex" or "binary". | + +### Returns + +| Type | Description | +| -------------- | ----------- | +| string / Array | The hash digest as string (for "base64", "base64url", "base64rawurl", "hex" `outputEncoding`) or raw array of integers (for "binary" `outputEncoding`). | + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + let hash = crypto.md5('hello world!', 'hex'); + console.log(hash); + let binArray = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]; + hash = crypto.md5(new Uint8Array(binArray).buffer, 'hex'); + console.log(hash); +} +``` + + + +The above script should result in the following being printed during execution: + +```bash +INFO[0000] fc3ff98e8c6a0d3087d515c0473f8677 +INFO[0000] fc3ff98e8c6a0d3087d515c0473f8677 +``` diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/06-randomBytes- int -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/06-randomBytes- int -.md new file mode 100644 index 0000000000..43b837e219 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/06-randomBytes- int -.md @@ -0,0 +1,32 @@ +--- +title: 'randomBytes( int )' +description: 'randomBytes.' +excerpt: 'randomBytes.' +--- + +Return an array with a number of cryptographically random bytes. It will either return exactly the amount of bytes requested or will throw an exception if something went wrong. + +| Parameter | Type | Description | +| --------- | ------- | --------------------------------- | +| int | integer | The length of the returned array. | + +### Returns + +| Type | Description | +| ----- | --------------------------------------------- | +| Array | An array with cryptographically random bytes. | + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + const bytes = crypto.randomBytes(42); + console.log(bytes); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/07-ripemd160- input- outputEncoding -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/07-ripemd160- input- outputEncoding -.md new file mode 100644 index 0000000000..42952973ca --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/07-ripemd160- input- outputEncoding -.md @@ -0,0 +1,44 @@ +--- +title: 'ripemd160( input, outputEncoding )' +description: 'Use RIPEMD-160 to hash input data.' +excerpt: 'Use RIPEMD-160 to hash input data.' +--- + +Use [ripemd160](https://pkg.go.dev/golang.org/x/crypto/ripemd160) to hash input data. + +| Parameter | Type | Description | +| -------------- | -------------------- | --------------------------------------------------| +| input | string / ArrayBuffer (≥ v0.31.0) | The input string or `ArrayBuffer` object to hash. | +| outputEncoding | string | Describes the type of encoding to use for the hash value. Can be "base64", "base64url", "base64rawurl", "hex" or "binary". | + +### Returns + +| Type | Description | +| -------------- | ----------- | +| string / Array | The hash digest as string (for "base64", "base64url", "base64rawurl", "hex" `outputEncoding`) or raw array of integers (for "binary" `outputEncoding`). | + + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + let hash = crypto.ripemd160('hello world!', 'hex'); + console.log(hash); + let binArray = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]; + hash = crypto.ripemd160(new Uint8Array(binArray).buffer, 'hex'); + console.log(hash); +} +``` + + + +The above script should result in the following being printed during execution: + +```bash +INFO[0000] dffd03137b3a333d5754813399a5f437acd694e5 +INFO[0000] dffd03137b3a333d5754813399a5f437acd694e5 +``` diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/08-sha1- input- outputEncoding -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/08-sha1- input- outputEncoding -.md new file mode 100644 index 0000000000..7b9dc28b82 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/08-sha1- input- outputEncoding -.md @@ -0,0 +1,44 @@ +--- +title: 'sha1( input, outputEncoding )' +description: 'Use SHA-1 to hash input data.' +excerpt: 'Use SHA-1 to hash input data.' +--- + +Use [sha1](https://golang.org/pkg/crypto/sha1/) to hash input data. + +| Parameter | Type | Description | +| -------------- | -------------------- | --------------------------------------------------| +| input | string / ArrayBuffer (≥ v0.31.0) | The input string or `ArrayBuffer` object to hash. | +| outputEncoding | string | Describes the type of encoding to use for the hash value. Can be "base64", "base64url", "base64rawurl", "hex" or "binary". | + +### Returns + +| Type | Description | +| -------------- | ----------- | +| string / Array | The hash digest as string (for "base64", "base64url", "base64rawurl", "hex" `outputEncoding`) or raw array of integers (for "binary" `outputEncoding`). | + + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + let hash = crypto.sha1('hello world!', 'hex'); + console.log(hash); + let binArray = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]; + hash = crypto.sha1(new Uint8Array(binArray).buffer, 'hex'); + console.log(hash); +} +``` + + + +The above script should result in the following being printed during execution: + +```bash +INFO[0000] 430ce34d020724ed75a196dfc2ad67c77772d169 +INFO[0000] 430ce34d020724ed75a196dfc2ad67c77772d169 +``` diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/09-sha256- input- outputEncoding -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/09-sha256- input- outputEncoding -.md new file mode 100644 index 0000000000..7b0c8c4520 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/09-sha256- input- outputEncoding -.md @@ -0,0 +1,44 @@ +--- +title: 'sha256( input, outputEncoding )' +description: 'Use SHA-256 to hash input data.' +excerpt: 'Use SHA-256 to hash input data.' +--- + +Use [sha256](https://golang.org/pkg/crypto/sha256/) to hash input data. + +| Parameter | Type | Description | +| -------------- | -------------------- | --------------------------------------------------| +| input | string / ArrayBuffer (≥ v0.31.0) | The input string or `ArrayBuffer` object to hash. | +| outputEncoding | string | Describes the type of encoding to use for the hash value. Can be "base64", "base64url", "base64rawurl", "hex" or "binary". | + +### Returns + +| Type | Description | +| -------------- | ----------- | +| string / Array | The hash digest as string (for "base64", "base64url", "base64rawurl", "hex" `outputEncoding`) or raw array of integers (for "binary" `outputEncoding`). | + + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + let hash = crypto.sha256('hello world!', 'hex'); + console.log(hash); + let binArray = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]; + hash = crypto.sha256(new Uint8Array(binArray).buffer, 'hex'); + console.log(hash); +} +``` + + + +The above script should result in the following being printed during execution: + +```bash +INFO[0000] 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9 +INFO[0000] 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9 +``` diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/10-sha384- input- outputEncoding -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/10-sha384- input- outputEncoding -.md new file mode 100644 index 0000000000..b7ddc4e5a0 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/10-sha384- input- outputEncoding -.md @@ -0,0 +1,44 @@ +--- +title: 'sha384( input, outputEncoding )' +description: 'Use SHA-384 to hash input data.' +excerpt: 'Use SHA-384 to hash input data.' +--- + +Use [sha384](https://golang.org/pkg/crypto/sha512/) to hash input data. + +| Parameter | Type | Description | +| -------------- | -------------------- | --------------------------------------------------| +| input | string / ArrayBuffer (≥ v0.31.0) | The input string or `ArrayBuffer` object to hash. | +| outputEncoding | string | Describes the type of encoding to use for the hash value. Can be "base64", "base64url", "base64rawurl", "hex" or "binary". | + +### Returns + +| Type | Description | +| -------------- | ----------- | +| string / Array | The hash digest as string (for "base64", "base64url", "base64rawurl", "hex" `outputEncoding`) or raw array of integers (for "binary" `outputEncoding`). | + + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + let hash = crypto.sha384('hello world!', 'hex'); + console.log(hash); + let binArray = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]; + hash = crypto.sha384(new Uint8Array(binArray).buffer, 'hex'); + console.log(hash); +} +``` + + + +The above script should result in the following being printed during execution: + +```bash +INFO[0000] d33d40f7010ce34aa86efd353630309ed5c3d7ffac66d988825cf699f4803ccdf3f033230612f0945332fb580d8af805 +INFO[0000] d33d40f7010ce34aa86efd353630309ed5c3d7ffac66d988825cf699f4803ccdf3f033230612f0945332fb580d8af805 +``` diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/11-sha512- input- outputEncoding -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/11-sha512- input- outputEncoding -.md new file mode 100644 index 0000000000..8d1498e8c1 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/11-sha512- input- outputEncoding -.md @@ -0,0 +1,44 @@ +--- +title: 'sha512( input, outputEncoding )' +description: 'Use SHA-512 to hash input data.' +excerpt: 'Use SHA-512 to hash input data.' +--- + +Use [sha512](https://golang.org/pkg/crypto/sha512/) to hash input data. + +| Parameter | Type | Description | +| -------------- | -------------------- | --------------------------------------------------| +| input | string / ArrayBuffer (≥ v0.31.0) | The input string or `ArrayBuffer` object to hash. | +| outputEncoding | string | Describes the type of encoding to use for the hash value. Can be "base64", "base64url", "base64rawurl", "hex" or "binary". | + +### Returns + +| Type | Description | +| -------------- | ----------- | +| string / Array | The hash digest as string (for "base64", "base64url", "base64rawurl", "hex" `outputEncoding`) or raw array of integers (for "binary" `outputEncoding`). | + + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + let hash = crypto.sha512('hello world!', 'hex'); + console.log(hash); + let binArray = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]; + hash = crypto.sha512(new Uint8Array(binArray).buffer, 'hex'); + console.log(hash); +} +``` + + + +The above script should result in the following being printed during execution: + +```bash +INFO[0000] db9b1cd3262dee37756a09b9064973589847caa8e53d31a9d142ea2701b1b28abd97838bb9a27068ba305dc8d04a45a1fcf079de54d607666996b3cc54f6b67c +INFO[0000] db9b1cd3262dee37756a09b9064973589847caa8e53d31a9d142ea2701b1b28abd97838bb9a27068ba305dc8d04a45a1fcf079de54d607666996b3cc54f6b67c +``` diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/12-sha512_256- input- outputEncoding -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/12-sha512_256- input- outputEncoding -.md new file mode 100644 index 0000000000..79bfe4f38e --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/12-sha512_256- input- outputEncoding -.md @@ -0,0 +1,44 @@ +--- +title: 'sha512_256( input, outputEncoding )' +description: 'Use SHA-512/256 to hash input data.' +excerpt: 'Use SHA-512/256 to hash input data.' +--- + +Use [sha512_256](https://golang.org/pkg/crypto/sha512/) to hash input data. + +| Parameter | Type | Description | +| -------------- | -------------------- | --------------------------------------------------| +| input | string / ArrayBuffer (≥ v0.31.0) | The input string or `ArrayBuffer` object to hash. | +| outputEncoding | string | Describes the type of encoding to use for the hash value. Can be "base64", "base64url", "base64rawurl", "hex" or "binary". | + +### Returns + +| Type | Description | +| -------------- | ----------- | +| string / Array | The hash digest as string (for "base64", "base64url", "base64rawurl", "hex" `outputEncoding`) or raw array of integers (for "binary" `outputEncoding`). | + + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + let hash = crypto.sha512_256('hello world!', 'hex'); + console.log(hash); + let binArray = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]; + hash = crypto.sha512_256(new Uint8Array(binArray).buffer, 'hex'); + console.log(hash); +} +``` + + + +The above script should result in the following being printed during execution: + +```bash +INFO[0000] 595b5926068b4828fb1c27db21281e31118b8475cb6c3ceeb09be7b685414d5f +INFO[0000] 595b5926068b4828fb1c27db21281e31118b8475cb6c3ceeb09be7b685414d5f +``` diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/13-sha512_224- input- outputEncoding -.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/13-sha512_224- input- outputEncoding -.md new file mode 100644 index 0000000000..d3668b02a4 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/13-sha512_224- input- outputEncoding -.md @@ -0,0 +1,44 @@ +--- +title: 'sha512_224( input, outputEncoding )' +description: 'Use SHA-512/224 to hash input data.' +excerpt: 'Use SHA-512/224 to hash input data.' +--- + +Use [sha512_224](https://golang.org/pkg/crypto/sha512/) to hash input data. + +| Parameter | Type | Description | +| -------------- | -------------------- | --------------------------------------------------| +| input | string / ArrayBuffer (≥ v0.31.0) | The input string or `ArrayBuffer` object to hash. | +| outputEncoding | string | Describes the type of encoding to use for the hash value. Can be "base64", "base64url", "base64rawurl", "hex" or "binary". | + +### Returns + +| Type | Description | +| -------------- | ----------- | +| string / Array | The hash digest as string (for "base64", "base64url", "base64rawurl", "hex" `outputEncoding`) or raw array of integers (for "binary" `outputEncoding`). | + + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + let hash = crypto.sha512_224('hello world!', 'hex'); + console.log(hash); + let binArray = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]; + hash = crypto.sha512_224(new Uint8Array(binArray).buffer, 'hex'); + console.log(hash); +} +``` + + + +The above script should result in the following being printed during execution: + +```bash +INFO[0000] bc4ed196f7ba1c20f6fb6be1f91edf8293a35b065d6e7d6fd368c890 +INFO[0000] bc4ed196f7ba1c20f6fb6be1f91edf8293a35b065d6e7d6fd368c890 +``` diff --git a/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/80-Hasher.md b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/80-Hasher.md new file mode 100644 index 0000000000..63b91d3061 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/03 k6-crypto/80-Hasher.md @@ -0,0 +1,38 @@ +--- +title: 'Hasher' +description: 'Object returned by crypto.createHash(). It allows adding more data to be hashed and to extract digests along the way.' +excerpt: 'Object returned by crypto.createHash(). It allows adding more data to be hashed and to extract digests along the way.' +--- + +This object is returned by [crypto.createHash()](/javascript-api/v0-31/k6-crypto/createhash-algorithm) +and allows the user to successively add more string data to be hashed, and to extract digests along the way. + +| Name | Type | Description | +| --------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Hasher.update(string) | function | Add more data to the string we want to create a hash of. Takes one string argument, which is the new data we want to add. | +| Hasher.digest(string) | function | Return a digest from the data added (using update()) to the Hasher object so far. Takes one string argument, which is the encoding format to return. This can be either "hex" or "base64". | + +### Example + + + +```javascript +import crypto from 'k6/crypto'; + +export default function () { + console.log(crypto.sha256('hello world!', 'hex')); + let hasher = crypto.createHash('sha256'); + hasher.update('hello '); + hasher.update('world!'); + console.log(hasher.digest('hex')); +} +``` + + + +The above code sample should produce this in its output: + +```bash +INFO[0000] 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9 +INFO[0000] 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9 +``` diff --git a/src/data/markdown/versioned-js-api/v0.31/04 k6-data.md b/src/data/markdown/versioned-js-api/v0.31/04 k6-data.md new file mode 100644 index 0000000000..d76842676a --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/04 k6-data.md @@ -0,0 +1,10 @@ +--- +title: "k6/data" +excerpt: "k6 data API" +--- + +The data module, added in k6 v0.30.0, provides helpers to work with data. + +| Class/Method | Description | +| ----- | ----------- | +| [SharedArray](/javascript-api/v0-31/k6-data/sharedarray) | read-only array like structure that shares memory between VUs | diff --git a/src/data/markdown/versioned-js-api/v0.31/04 k6-data/1-SharedArray.md b/src/data/markdown/versioned-js-api/v0.31/04 k6-data/1-SharedArray.md new file mode 100644 index 0000000000..b59a0015f0 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/04 k6-data/1-SharedArray.md @@ -0,0 +1,97 @@ +--- +title: SharedArray +excerpt: 'SharedArray is an array-like object that shares the underlying memory between VUs.' +--- + +`SharedArray` is an array-like object that shares the underlying memory between VUs. Its constructor takes a name for the `SharedArray` and a function which needs to return an array object itself. The function will be executed only once and its result will then be saved in memory once and copies of the elements will be given when requested. The name is needed as VUs are completely separate JS VMs and k6 needs some way to identify the `SharedArray`s that it needs to return. + +This does mean that you can have multiple such ones and even only load some of them for given VUs, although that is unlikely to have any performance benefit. + +Everything about `SharedArray` is read-only once it is constructed, so it is not possible to communicate between VUs using it. + +Supported operations include: +1. getting the number of elements with `length` +2. getting an element by its index using the normal syntax `array[index]` +3. using `for-of` loops + +Which means that for the most part if you currently have an array data structure that you want to take less memory you can just wrap it in `SharedArray` and it should work for most cases. + +### Examples + +
+ +```javascript +import { SharedArray } from "k6/data"; + +var data = new SharedArray("some name", function() { + // here you can open files, and then do additional processing on them or just generate the data dynamically + var f = JSON.parse(open("./somefile.json")).; + return f; // f must be an array +}); + +export default () => { + var element = data[Math.floor(Math.random() * data.length)] + // do something with element +} +``` + +
+ +## Performance characteristics + +As the `SharedArray` is keeping the data marshalled as JSON and unmarshals elements when requested it does take additional time to unmarshal JSONs and generate objects that then need to be garbage collected. + +This in general should be unnoticeable compared to whatever you are doing with the data, but might mean that for small sets of data it is better to not use `SharedArray`, although your mileage may vary. + +As an example the following script: + +
+ +```javascript +import {check} from "k6"; +import http from "k6/http"; +import {SharedArray} from "k6/data" + +var n = parseInt(__ENV.N) +function generateArray() { + var arr = new Array(n); + for (var i = 0; i< n; i++){ + arr[i] = {"something": "something else" +i, "password": "12314561" } + } + return arr +} + +var data; +if (__ENV.SHARED === "true") { + data = new SharedArray("my data", generateArray); +} else { + data = generateArray(); +} + +export default function () { + var iterationData = data[Math.floor(Math.random() * data.length)]; + var res = http.post("https://httpbin.test.k6.io/anything", JSON.stringify(iterationData), {headers: {"Content-type": "application/json"}}) + check(res, {"status 200": (r) => r.status === 200}) +} +``` + +
+ +Which was ran with v0.31.0 and 100 VUs. As can be seen from the table below, there isn't much of a difference at lower numbers of data lines - up until around 1000 data lines there is little benefit in memory usage. But also there is little to no difference in CPU usage as well. At 10k and above, the memory savings start to heavily translate to CPU ones. + +| data lines | shared | wall time | CPU % | MEM usage | http requests | +| --- | --- | --- | --- | ---- | --- | +| 100 | true | 2:01:70 | 70-79% | 213-217MB | 92191-98837 | +| 100 | false | 2:01:80 | 74-75% | 224-232MB | 96851-98643 | +| 1000 | true | 2:01:60 | 74-79% | 209-216MB | 98251-98806 | +| 1000 | false | 2:01:90 | 75-77% | 333-339MB | 98069-98951 | +| 10000 | true | 2:01:70 | 78-79% | 213-217MB | 97953-98735 | +| 10000 | false | 2:03:00 | 80-83% | 1364-1400MB | 96816-98852 | +| 100000 | true | 2:02:20 | 78-79% | 238-275MB | 98103-98540 | +| 100000 | false | 2:14:00 | 120-124% | 8.3-9.1GB | 96003-97802 | + +In v0.30.0 the difference in CPU usage at lower numbers was around 10-15%, but it also started to even out at around 10k data lines and was a clear winner at 100k. + +The CPU/memory data comes from using `/usr/bin/time` and the raw data can be found [here](https://gist.github.com/MStoykov/1181cfa6f00bc56b90915155f885e2bb). + +These numbers are purely illustrative as the performance can be affected by any additional processing of the element retrieved from the `SharedArray`, or if an output is in use, or it gets multiple elements, etc. While `SharedArray` has some CPU usage it might turn out that it will be negligible in a given situation with just 10 elements or more problematic than the memory usage for a 100k elements. So if in doubt you should probably run some benchmarks and decide which tradeoffs are more important for your use case. diff --git a/src/data/markdown/versioned-js-api/v0.31/05 k6-encoding.md b/src/data/markdown/versioned-js-api/v0.31/05 k6-encoding.md new file mode 100644 index 0000000000..48c7e5633f --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/05 k6-encoding.md @@ -0,0 +1,11 @@ +--- +title: "k6/encoding" +excerpt: 'The encoding module provides base64 encoding/decoding as defined by RFC4648.' +--- +The encoding module provides [base64](https://en.wikipedia.org/wiki/Base64) +encoding/decoding as defined by [RFC4648](https://tools.ietf.org/html/rfc4648). + +| Function | Description | +| -------- | ----------- | +| [b64decode(input, [encoding])](/javascript-api/v0-31/k6-encoding/b64decode-input-encoding) | Base64 decode a string. | +| [b64encode(input, [encoding])](/javascript-api/v0-31/k6-encoding/b64encode-input-encoding) | Base64 encode a string. | diff --git a/src/data/markdown/versioned-js-api/v0.31/05 k6-encoding/b64decode- input- -encoding- -.md b/src/data/markdown/versioned-js-api/v0.31/05 k6-encoding/b64decode- input- -encoding- -.md new file mode 100644 index 0000000000..fff8cf17ef --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/05 k6-encoding/b64decode- input- -encoding- -.md @@ -0,0 +1,38 @@ +--- +title: 'b64decode( input, [encoding] )' +description: 'Base64 decode a string.' +excerpt: 'Base64 decode a string.' +--- + +Decode the passed base64 encoded `input` string into the unencoded original string. + +| Parameter | Type | Description | +| ------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| input | string | The string to base64 decode. | +| encoding (optional) | string | The base64 encoding to use.
Available options are:
- **"std"**: the standard encoding with `=` padding chars and `+` and `/` characters in encoding alphabet. This is the default.
- **"rawstd"**: like `std` but without `=` padding characters.
- **"url"**: URL safe version of `std`, encoding alphabet doesn't contain `+` and `/` characters, but rather `-` and `_` characters.
- **"rawurl"**: like `url` but without `=` padding characters. | + +### Returns + +| Type | Description | +| ------ | ------------------------------------------------- | +| string | The base64 decoded version of the `input` string. | + +### Example + + + +```javascript +import { check } from 'k6'; +import encoding from 'k6/encoding'; + +export default function () { + let str = 'hello world'; + let enc = 'aGVsbG8gd29ybGQ='; + check(null, { + 'is encoding correct': () => encoding.b64encode(str) === enc, + 'is decoding correct': () => encoding.b64decode(enc) === str, + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/05 k6-encoding/b64encode- input- -encoding- -.md b/src/data/markdown/versioned-js-api/v0.31/05 k6-encoding/b64encode- input- -encoding- -.md new file mode 100644 index 0000000000..51f606fec6 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/05 k6-encoding/b64encode- input- -encoding- -.md @@ -0,0 +1,38 @@ +--- +title: 'b64encode( input, [encoding] )' +description: 'Encode data in base64.' +excerpt: 'Encode data in base64.' +--- + +| Parameter | Type | Description | +| ------------------- | ------ | ------------------------------------------------------------------------ | +| input | string / ArrayBuffer (≥ v0.31.0) | The input string or `ArrayBuffer` object to base64 encode. | +| encoding (optional) | string | The base64 encoding to use.
Available options are:
- **"std"**: the standard encoding with `=` padding chars and `+` and `/` characters in encoding alphabet. This is the default.
- **"rawstd"**: like `std` but without `=` padding characters.
- **"url"**: URL safe version of `std`, encoding alphabet doesn't contain `+` and `/` characters, but rather `-` and `_` characters.
- **"rawurl"**: like `url` but without `=` padding characters. | + +### Returns + +| Type | Description | +| ------ | ---------------------------------------- | +| string | The base64 encoding of the `input` data. | + +### Example + + + +```javascript +import { check } from 'k6'; +import encoding from 'k6/encoding'; + +export default function () { + let str = 'hello world'; + let enc = 'aGVsbG8gd29ybGQ='; + let buf = new Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]).buffer; + check(null, { + 'is encoding correct': () => encoding.b64encode(str) === enc, + 'is decoding correct': () => encoding.b64decode(enc) === str, + 'is encoding ArrayBuffer correct': () => encoding.b64encode(buf) === enc, + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html.md new file mode 100644 index 0000000000..a0a2b58218 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html.md @@ -0,0 +1,14 @@ +--- +title: "k6/html" +excerpt: 'The k6/html module contains functionality for HTML parsing.' +--- +The k6/html module contains functionality for HTML parsing. + +| Function | Description | +| -------- | ----------- | +| [parseHTML(src)](/javascript-api/v0-31/k6-html/parsehtml-src) | Parse an HTML string and populate a [Selection](/javascript-api/v0-31/k6-html/selection) object. | + +| Class | Description | +| -------- | ----------- | +| [Element](/javascript-api/v0-31/k6-html/element) | An HTML DOM element as returned by the [Selection](/javascript-api/v0-31/k6-html/selection) API. | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A jQuery-like API for accessing HTML DOM elements. | diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/10-parseHTML- src -.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/10-parseHTML- src -.md new file mode 100644 index 0000000000..571401f041 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/10-parseHTML- src -.md @@ -0,0 +1,35 @@ +--- +title: 'parseHTML( src )' +description: 'Parse an HTML string and populate a Selection object.' +excerpt: 'Parse an HTML string and populate a Selection object.' +--- + +Parse an HTML string and populate a [Selection](/javascript-api/v0-31/k6-html/selection) object. + +| Parameter | Type | Description | +| --------- | ------ | ------------ | +| src | string | HTML source. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------------- | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection object. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import http from 'k6/http'; + +export default function () { + const res = http.get('https://k6.io'); + const doc = parseHTML(res.body); // equivalent to res.html() + const pageTitle = doc.find('head title').text(); + const langAttr = doc.find('html').attr('lang'); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/20-Element -k6-html-.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/20-Element -k6-html-.md new file mode 100644 index 0000000000..3e0a6159b9 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/20-Element -k6-html-.md @@ -0,0 +1,160 @@ +--- +title: 'Element' +description: 'An HTML DOM element as returned by the Selection API.' +excerpt: 'An HTML DOM element as returned by the Selection API.' +--- + +Represents a DOM element matched by a [Selection](/javascript-api/v0-31/k6-html/selection), +and provides an API to inspect the element content. + +Use [Selection.get(index)](/javascript-api/v0-31/k6-html/selection/selection-get-index) to return an Element object. + +The Element object provides a similar API to the [DOM Element API](https://developer.mozilla.org/en-US/Web/API/Element) to retrieve element information. + +| Method | Description | +| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| nodeName | The name of the element. | +| nodeType | The type of the element. | +| nodeValue | The element value. | +| id | The id of the element. | +| innerHTML | Is a DOMString representing the markup of the element's content. | +| textContent | The element content. | +| ownerDocument | [Element](/javascript-api/v0-31/k6-html/element) | +| attributes | An array of attributes. | +| firstChild | [Element](/javascript-api/v0-31/k6-html/element) | +| lastChild | [Element](/javascript-api/v0-31/k6-html/element) | +| childElementCount | The number of children elements. | +| firstElementChild | [Element](/javascript-api/v0-31/k6-html/element) | +| lastElementChild | [Element](/javascript-api/v0-31/k6-html/element) | +| previousSibling | [Element](/javascript-api/v0-31/k6-html/element) | +| nextSibling | [Element](/javascript-api/v0-31/k6-html/element) | +| previousElementSibling | [Element](/javascript-api/v0-31/k6-html/element) | +| nextElementSibling | [Element](/javascript-api/v0-31/k6-html/element) | +| parentElement | [Element](/javascript-api/v0-31/k6-html/element) | +| parentNode | [Element](/javascript-api/v0-31/k6-html/element) | +| childNodes | Array of [Element](/javascript-api/v0-31/k6-html/element) | +| children | Array of [Element](/javascript-api/v0-31/k6-html/element) | +| classList | An array of class names. | +| className | The class name string | +| lang | The value of the lang attribute. | +| toString | The element string representation. | +| hasAttribute | Boolean | +| getAttribute | getAttributeNode | +| hasAttributes | Boolean | +| hasChildNodes | Boolean | +| isSameNode | Boolean | +| isEqualNode | Boolean | +| getElementsByClassName | Return an array of [Element](/javascript-api/v0-31/k6-html/element). | +| getElementsByTagName | Return an array of [Element](/javascript-api/v0-31/k6-html/element). | +| querySelector | Returns the first [Element](/javascript-api/v0-31/k6-html/element) which matches the specified selector string relative to the element | +| querySelectorAll | Returns all the [Element](/javascript-api/v0-31/k6-html/element) which matches the specified selector string relative to the element | +| contains | | +| matches | Returns a Boolean indicating whether or not the element would be selected by the specified selector string | +| namespaceURI | The namespace URI of the element. | +| isDefaultNamespace | Returns a Boolean indicating whether the element has the default namespace. | + +Additionally, Element can provide more methods depending on the Element type. + +- **AnchorElement**: hash, host, hostname, port, username, password, origin, pathname, protocol, relist, search, text. + +- **ButtonElement**: form, formAction, formEnctype, formMethod, formNoValidate, formTarget, labels, name, value. + +- **CanvasElement**: width, height + +- **DataListElement**: options + +- **FieldSetElement**: elements, type, form + +- **FormElement**: elements, length, method + +- **InputElement**: form + +- **LabelElement**: control, form + +- **LegendElement**: form + +- **LinkElement**: relList + +- **MapElement**: areas, images + +- **ObjectElement**: form + +- **OptionElement**: disabled, form, index, label, text, value + +- **OutputElement**: value, labels + +- **ProgressElement**: max, value, position + +- **ScriptElement**: text + +- **SelectElement**: form, length, options, selectedOptions, selectedIndex, value + +- **StyleElement**: text + +- **TableElement**: caption, thead, tbody, tfoot, rows + +- **TableCellElement**: cellIndex, colSpan, rowSpan, headers + +- **TableRowElement**: cells, colSpan, sectionRowIndex, rowIndex + +- **VideoElement**: textTracks + +- **TitleElement**: text + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
Value term 1
+
Value term 2
+
+ `; + const sel = parseHTML(content).find('dl').children(); + + const el1 = sel.get(0); + const el2 = sel.get(1); + + console.log(el1.nodeName()); + console.log(el1.id()); + console.log(el1.textContent()); + + console.log(el2.nodeName()); + console.log(el2.id()); + console.log(el2.textContent()); + + sleep(1); +} +``` + +
+ + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +\t6 + `; + const el = parseHTML(content).find('a').get(0); + + console.log(el.nodeName()); + console.log(el.innerHTML()); + console.log(el.host()); + console.log(el.hostname()); + console.log(el.protocol()); + + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection.md new file mode 100644 index 0000000000..f23184d69d --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection.md @@ -0,0 +1,69 @@ +--- +title: 'Selection' +description: 'A jQuery-like API for accessing HTML DOM elements.' +excerpt: 'A jQuery-like API for accessing HTML DOM elements.' +--- + +Represents a set of nodes in a DOM tree. + +Selections have a jQuery-compatible API, but with two caveats: + +- CSS and screen layout are not processed, thus calls like css() and offset() are unavailable. +- DOM trees are read-only, you can't set attributes or otherwise modify nodes. + +(Note that the read-only nature of the DOM trees is purely to avoid a maintenance burden on code with seemingly no practical use - if a compelling use case is presented, modification can easily be implemented.) + +| Method | Description | +| ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| [Selection.attr(name)](/javascript-api/v0-31/k6-html/selection/selection-attr-name) | Get the value of an attribute for the first element in the Selection. | +| [Selection.children([selector])](/javascript-api/v0-31/k6-html/selection/selection-children-selector) | Get the children of each element in the set of matched elements, optionally filtered by a selector. | +| [Selection.closest(selector)](/javascript-api/v0-31/k6-html/selection/selection-closest-selector) | Get the first element that matches the selector by testing the element itself and traversing up through its ancestors | +| [Selection.contents()](/javascript-api/v0-31/k6-html/selection/selection-contents) | Get the children of each element in the set of matched elements, including text and comment nodes. | +| [Selection.data([key])](/javascript-api/v0-31/k6-html/selection/selection-data-key) | Return the value at the named data store for the first element in the set of matched elements. | +| [Selection.each(fn)](/javascript-api/v0-31/k6-html/selection/selection-each-fn) | Iterate and execute a function for each matched element. | +| [Selection.eq(index)](/javascript-api/v0-31/k6-html/selection/selection-eq-index) | Reduce the set of matched elements to the one at the specified index. | +| [Selection.filter(selector)](/javascript-api/v0-31/k6-html/selection/selection-filter-selector) | Reduce the set of matched elements to those that match the selector or pass the function's test. | +| [Selection.find(selector)](/javascript-api/v0-31/k6-html/selection/selection-find-selector) | Find the selection descendants, filtered by a selector. | +| [Selection.first()](/javascript-api/v0-31/k6-html/selection/selection-first) | Reduce the set of matched elements to the first in the set. | +| [Selection.get(index)](/javascript-api/v0-31/k6-html/selection/selection-get-index) | Retrieve the [Element (k6/html)](/javascript-api/v0-31/k6-html/element) matched by the selector | +| [Selection.has(selector)](/javascript-api/v0-31/k6-html/selection/selection-has-selector) | Reduce the set of matched elements to those that have a descendant that matches the selector | +| [Selection.html()](/javascript-api/v0-31/k6-html/selection/selection-html) | Get the HTML contents of the first element in the set of matched elements | +| [Selection.is(selector)](/javascript-api/v0-31/k6-html/selection/selection-is-selector) | Check the current matched set of elements against a selector or element and return true if at least one of these elements matches the given arguments. | +| [Selection.last()](/javascript-api/v0-31/k6-html/selection/selection-last) | Reduce the set of matched elements to the final one in the set. | +| [Selection.map(fn)](/javascript-api/v0-31/k6-html/selection/selection-map-fn) | Pass each element in the current matched set through a function, producing a new Array containing the return values. | +| [Selection.nextAll([selector])](/javascript-api/v0-31/k6-html/selection/selection-nextall-selector) | Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. | +| [Selection.next([selector])](/javascript-api/v0-31/k6-html/selection/selection-next-selector) | Get the immediately following sibling of each element in the set of matched element | +| [Selection.nextUntil([selector], [filter])](/javascript-api/v0-31/k6-html/selection/selection-nextuntil-selector-filter) | Get all following siblings of each element up to but not including the element matched by the selector. | +| [Selection.not(selector)](/javascript-api/v0-31/k6-html/selection/selection-not-selector) | Remove elements from the set of matched elements | +| [Selection.parent([selector])](/javascript-api/v0-31/k6-html/selection/selection-parent-selector) | Get the parent of each element in the current set of matched elements, optionally filtered by a selector. | +| [Selection.parents([selector])](/javascript-api/v0-31/k6-html/selection/selection-parents-selector) | Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. | +| [Selection.parentsUntil([selector], [filter])](/javascript-api/v0-31/k6-html/selection/selection-parentsuntil-selector-filter) | Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector. | +| [Selection.prevAll([selector])](/javascript-api/v0-31/k6-html/selection/selection-prevall-selector) | Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. | +| [Selection.prev([selector])](/javascript-api/v0-31/k6-html/selection/selection-prev-selector) | Get the immediately preceding sibling of each element in the set of matched elements. | +| [Selection.prevUntil([selector], [filter])](/javascript-api/v0-31/k6-html/selection/selection-prevuntil-selector-filter) | Get all preceding siblings of each element up to but not including the element matched by the selector. | +| [Selection.size()](/javascript-api/v0-31/k6-html/selection/selection-size) | Return the number of elements in the Selection. | +| [Selection.serialize()](/javascript-api/v0-31/k6-html/selection/selection-size) | Encode a set of form elements as a string in standard URL-encoded notation for submission. | +| [Selection.serializeArray()](/javascript-api/v0-31/k6-html/selection/selection-size) | Encode a set of form elements as an array of names and values. | +| [Selection.serializeObject()](/javascript-api/v0-31/k6-html/selection/selection-serializeobject) | Encode a set of form elements as an object. | +| [Selection.slice(start [, end])](/javascript-api/v0-31/k6-html/selection/selection-slice-start-end) | Reduce the set of matched elements to a subset specified by a range of indices. | +| [Selection.text()](/javascript-api/v0-31/k6-html/selection/selection-text) | Get the text content of the selection. | +| [Selection.toArray()](/javascript-api/v0-31/k6-html/selection/selection-toarray) | Retrieve all the elements contained in the Selection, as an array. | +| [Selection.val()](/javascript-api/v0-31/k6-html/selection/selection-val) | Get the current value of the first element in the set of matched elements. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import http from 'k6/http'; + +export default function () { + const res = http.get('https://k6.io'); + const doc = parseHTML(res.body); + const pageTitle = doc.find('head title').text(); + const langAttr = doc.find('html').attr('lang'); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-attr-name-.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-attr-name-.md new file mode 100644 index 0000000000..58afda0ac1 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-attr-name-.md @@ -0,0 +1,34 @@ +--- +title: 'Selection.attr(name)' +excerpt: 'Get the value of an attribute for the first element in the Selection.' +--- + +Get the value of an attribute for the first element in the Selection. +Mimics [jquery.attr](https://api.jquery.com/attr/) + +| Parameter | Type | Description | +| --------- | ------ | -------------------------------- | +| name | string | The name of the attribute to get | + +### Returns + +| Type | Description | +| ------ | -------------------------- | +| string | The value of the attribute | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import http from 'k6/http'; + +export default function () { + const res = http.get('https://k6.io'); + const doc = parseHTML(res.body); + const langAttr = doc.find('html').attr('lang'); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-children--selector--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-children--selector--.md new file mode 100644 index 0000000000..ddf925ce0c --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-children--selector--.md @@ -0,0 +1,56 @@ +--- +title: 'Selection.children([selector])' +excerpt: 'Get the children of each element in the set of matched elements, optionally filtered by a selector.' +--- + +Get the children of each element in the set of matched elements, optionally filtered by a selector. +Mimics [jquery.children](https://api.jquery.com/children/) + +| Parameter | Type | Description | +| ------------------- | ------ | -------------------------------------------------------------------- | +| selector (optional) | string | A string containing a selector expression to match elements against. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ----------------------- | +| [Selection](/javascript-api/v0-31/k6-html/selection) | The children Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + const sel = doc.find('dl'); + + console.log(sel.children().size()); + console.log(sel.children('dt').size()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-closest-selector-.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-closest-selector-.md new file mode 100644 index 0000000000..fed534ad99 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-closest-selector-.md @@ -0,0 +1,55 @@ +--- +title: 'Selection.closest(selector)' +excerpt: 'For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.' +--- + +For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. +Mimics [jquery.closest](https://api.jquery.com/closest/) + +| Parameter | Type | Description | +| --------- | ------ | ------------------------------------------------------------------- | +| selector | string | A string containing a selector expression to match elements against | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ----------- | +| [Selection](/javascript-api/v0-31/k6-html/selection) | Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` + + `; + const doc = parseHTML(content); + + const sel = doc.find('li.item-a').closest('ul'); + console.log(sel.attr('class')); + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-contents--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-contents--.md new file mode 100644 index 0000000000..b0a307be8b --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-contents--.md @@ -0,0 +1,52 @@ +--- +title: 'Selection.contents()' +excerpt: 'Get the children of each element in the set of matched elements, including text and comment nodes.' +--- + +Get the children of each element in the set of matched elements, including text and comment nodes. +Mimics [jquery.contents](https://api.jquery.com/contents/). + +### Returns + +| Type | Description | +| ---------------------------------------------- | ----------- | +| [Selection](/javascript-api/v0-31/k6-html/selection) | Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + const sel = doc.find('dt'); + + console.log(sel.contents().text()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-data--key--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-data--key--.md new file mode 100644 index 0000000000..feb15dc0ab --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-data--key--.md @@ -0,0 +1,43 @@ +--- +title: 'Selection.data([key])' +excerpt: 'Return the value at the named data store for the first element in the set of matched elements.' +--- + +Return the value at the named data store for the first element in the set of matched elements. +Mimics [jquery.data](https://api.jquery.com/data/) + +| Parameter | Type | Description | +| -------------- | ------ | ----------------------------------------- | +| key (optional) | string | A string naming the piece of data to set. | + +### Returns + +| Type | Description | +| ------ | ---------------------------------- | +| string | The value at the named data store. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +

Hola

+ `; + + const doc = parseHTML(content); + const sel = doc.find('h1'); + + console.log(sel.data().testID); + console.log(sel.data('test-id')); + console.log(sel.data('testId')); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-each-fn-.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-each-fn-.md new file mode 100644 index 0000000000..365c54b94d --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-each-fn-.md @@ -0,0 +1,50 @@ +--- +title: 'Selection.each(fn)' +excerpt: 'Iterate over a Selection, executing a function for each matched element.' +--- + +Iterate over a [Selection](/javascript-api/v0-31/k6-html/selection), executing a function for each matched element. +Mimics [jquery.each](https://api.jquery.com/each/) + +| Parameter | Type | Description | +| --------- | -------- | --------------------------------------------------------- | +| fn | function | A function to iterate all the Elements of the Collection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + doc.find('dl').each(function (idx, el) { + console.log(el.innerHTML()); + }); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-eq-index-.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-eq-index-.md new file mode 100644 index 0000000000..ef5032e7d7 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-eq-index-.md @@ -0,0 +1,58 @@ +--- +title: 'Selection.eq(index)' +excerpt: 'Reduce the set of matched elements to the one at the specified index.' +--- + +Reduce the set of matched elements to the one at the specified index. +Mimics [jquery.eq](https://api.jquery.com/eq/). + +| Parameter | Type | Description | +| --------- | ------ | ---------------------------------------------------------- | +| index | Number | An integer indicating the 0-based position of the element. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + const sel = doc.find('dt'); + + console.log(sel.eq(0).html()); + console.log(sel.eq(1).html()); + console.log(sel.eq(2).html()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-filter-selector-.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-filter-selector-.md new file mode 100644 index 0000000000..572458df4f --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-filter-selector-.md @@ -0,0 +1,67 @@ +--- +title: 'Selection.filter(selector)' +excerpt: 'Reduce the set of matched elements to those that match the selector or pass the function test.' +--- + +Reduce the set of matched elements to those that match the selector or pass the function's test. +Mimics [jquery.filter](https://api.jquery.com/filter/) + +| Parameter | Type | Description | +| --------- | ---------------------------------------------- | -------------------------------------------------------------------- | +| selector | function | A function used as a test for each element in the set. | +| selector | string | A string containing a selector expression to match elements against. | +| selector | [Selection](/javascript-api/v0-31/k6-html/selection) | A selection to match elements against. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | --------------------- | +| [Selection](/javascript-api/v0-31/k6-html/selection) | The filter selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + let sel; + const els = doc.find('dl').children(); + + sel = els.filter('#term-2'); + console.log(sel.text()); + + sel = els.filter(function (idx, el) { + return el.text() === 'definition 3-a'; + }); + console.log(sel.text()); + + sel = els.filter(doc.find('dl dt#term-1')); + console.log(sel.text()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-find-selector-.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-find-selector-.md new file mode 100644 index 0000000000..e8a8b28926 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-find-selector-.md @@ -0,0 +1,36 @@ +--- +title: 'Selection.find(selector)' +excerpt: 'Find the selection descendants, filtered by a selector.' +--- + +Find the selection descendants, filtered by a selector. It returns a [Selection](/javascript-api/v0-31/k6-html/selection) object. +Mimics [jquery.find](https://api.jquery.com/find/) + +| Parameter | Type | Description | +| --------- | ------ | -------------------------------------------------------------------- | +| selector | string | A string containing a selector expression to match elements against. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ----------------- | +| [Selection](/javascript-api/v0-31/k6-html/selection) | Selection object. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import http from 'k6/http'; + +export default function () { + const res = http.get('https://k6.io'); + const doc = parseHTML(res.body); + + const titleDoc = doc.find('head title'); + const title = titleDoc.text(); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-first--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-first--.md new file mode 100644 index 0000000000..058e1b0570 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-first--.md @@ -0,0 +1,52 @@ +--- +title: 'Selection.first()' +excerpt: 'Reduce the set of matched elements to the first in the set.' +--- + +Reduce the set of matched elements to the first in the set. +Mimics [jquery.first](https://api.jquery.com/first/). + +### Returns + +| Type | Description | +| ---------------------------------------------- | ----------------------------------- | +| [Selection](/javascript-api/v0-31/k6-html/selection) | The first element of the Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + const sel = doc.find('dt'); + + console.log(sel.first().html()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-get-index-.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-get-index-.md new file mode 100644 index 0000000000..6fdf6be9a1 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-get-index-.md @@ -0,0 +1,57 @@ +--- +title: 'Selection.get(index)' +excerpt: 'Retrieve the Element matched by the selector.' +--- + +Retrieve the Element matched by the selector. +Mimics [jquery.get](https://api.jquery.com/get/) + +| Parameter | Type | Description | +| --------- | ------ | ---------------------------------------------------------- | +| index | Number | A zero-based integer indicating which element to retrieve. | + +### Returns + +| Type | Description | +| ------- | ------------------------------------ | +| Element | The Element matched by the selector. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + const sel = doc.find('dl').children(); + + console.log(sel.get(0).innerHTML()); + console.log(sel.get(1).innerHTML()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-has-selector-.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-has-selector-.md new file mode 100644 index 0000000000..71cb682507 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-has-selector-.md @@ -0,0 +1,51 @@ +--- +title: 'Selection.has(selector)' +excerpt: 'Reduce the set of matched elements to those that have a descendant that matches the selector.' +--- + +Reduce the set of matched elements to those that have a descendant that matches the selector. +Mimics [jquery.has](https://api.jquery.com/has/). + +| Parameter | Type | Description | +| --------- | ------ | -------------------------------------------------------------------- | +| selector | string | A string containing a selector expression to match elements against. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` + + `; + const doc = parseHTML(content); + + const sel = doc.find('li').has('ul'); + + console.log(sel.html()); + + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-html--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-html--.md new file mode 100644 index 0000000000..a1b12d19a7 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-html--.md @@ -0,0 +1,52 @@ +--- +title: 'Selection.html()' +excerpt: 'Get the HTML contents of the first element in the set of matched elements.' +--- + +Get the HTML contents of the first element in the set of matched elements. +Mimics [jquery.html](https://api.jquery.com/html/) + +### Returns + +| Type | Description | +| ------ | --------------------------------------------------------------------- | +| string | The HTML content of the first element in the set of matched elements. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + const sel = doc.find('dt'); + + console.log(sel.html()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-is-selector-.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-is-selector-.md new file mode 100644 index 0000000000..6065a3e2e6 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-is-selector-.md @@ -0,0 +1,69 @@ +--- +title: 'Selection.is(selector)' +excerpt: 'Check the current matched set of elements against a selector or element and return true if at least one of these elements matches the given arguments.' +--- + +Check the current matched set of elements against a selector or element and return true if at least one of these elements matches the given arguments. +Mimics [jquery.is](https://api.jquery.com/is/) + +| Parameter | Type | Description | +| --------- | ---------------------------------------------- | -------------------------------------------------------------------- | +| selector | function | A function used as a test for each element in the set | +| selector | string | A string containing a selector expression to match elements against. | +| selector | [Selection](/javascript-api/v0-31/k6-html/selection) | A selection. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | --------------------- | +| [Selection](/javascript-api/v0-31/k6-html/selection) | The filter selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + let result; + + const els = doc.find('dl').children(); + + result = els.is('dd'); + console.log(result); + + result = els.is(function (idx, el) { + return el.text() === 'hola'; + }); + console.log(result); + + result = els.is(els.first()); + console.log(result); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-last--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-last--.md new file mode 100644 index 0000000000..2ca0dabdcd --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-last--.md @@ -0,0 +1,52 @@ +--- +title: 'Selection.last()' +excerpt: 'Reduce the set of matched elements to the final one in the set.' +--- + +Reduce the set of matched elements to the final one in the set. +Mimics [jquery.last](https://api.jquery.com/last/). + +### Returns + +| Type | Description | +| ---------------------------------------------- | ----------------------------------- | +| [Selection](/javascript-api/v0-31/k6-html/selection) | The final element of the Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + const sel = doc.find('dt'); + + console.log(sel.last().html()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-map-fn-.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-map-fn-.md new file mode 100644 index 0000000000..309c059041 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-map-fn-.md @@ -0,0 +1,61 @@ +--- +title: 'Selection.map(fn)' +excerpt: 'Pass each element in the current matched set through a function, producing a new Array containing the return values.' +--- + +Pass each element in the current matched set through a function, producing a new Array containing the return values. +Mimics [jquery.each](https://api.jquery.com/each/) + +| Parameter | Type | Description | +| --------- | -------- | --------------------------------------------------------- | +| fn | function | A function to iterate all the Elements of the Collection. | + +### Returns + +| Type | Description | +| ----- | --------------------------------------- | +| Array | The array containing the return values. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + const newEls = doc + .find('dl') + .children() + .map(function (idx, el) { + return 'hola ' + el.text(); + }); + + console.log(newEls); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-next--selector--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-next--selector--.md new file mode 100644 index 0000000000..b2cb8a1061 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-next--selector--.md @@ -0,0 +1,48 @@ +--- +title: 'Selection.next([selector])' +excerpt: 'Get the immediately following sibling of each element in the set of matched elements +Mimics jquery.next.' +--- + +Get the immediately following sibling of each element in the set of matched elements +Mimics [jquery.next](https://api.jquery.com/next/). + +| Parameter | Type | Description | +| ------------------- | ------ | -------------------------------------------------------------------- | +| selector (optional) | string | A string containing a selector expression to match elements against. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` + + `; + const doc = parseHTML(content); + + const sel = doc.find('li.third-item').next(); + + console.log(sel.html()); + + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-nextAll--selector--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-nextAll--selector--.md new file mode 100644 index 0000000000..929b4739c3 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-nextAll--selector--.md @@ -0,0 +1,47 @@ +--- +title: 'Selection.nextAll([selector])' +excerpt: 'Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.' +--- + +Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. +Mimics [jquery.nextAll](https://api.jquery.com/nextAll/). + +| Parameter | Type | Description | +| ------------------- | ------ | ------------------------------------------------------------------- | +| selector (optional) | string | A string containing a selector expression to match elements against | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` + + `; + const doc = parseHTML(content); + + const sel = doc.find('li.third-item').nextAll(); + + console.log(sel.size()); + + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-nextUntil-selector-filter.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-nextUntil-selector-filter.md new file mode 100644 index 0000000000..a0b7df30ee --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-nextUntil-selector-filter.md @@ -0,0 +1,59 @@ +--- +title: 'Selection.nextUntil([selector], [filter])' +excerpt: 'Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.' +--- + +Get all following siblings of each element up to but not including the element matched by the selector. +Mimics [jquery.nextUntil](https://api.jquery.com/nextUntil/) + +| Parameter | Type | Description | +| ------------------- | ------------------------------------------------------------------ | ---------------------------------------------------------- | +| selector (optional) | string \| [Selection](/javascript-api/v0-31/k6-html/selection) \| `null` | A selector expression or object to match elements against. | +| filter (optional) | string \| `null` | A selector expression to filter matched elements. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + const sel = doc.find('#term-2').nextUntil('dt'); + console.log(sel.size()); + + const selFilter = doc.find('#term-1').nextUntil('#term-3', 'dd'); + console.log(selFilter.size()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-not-selector-.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-not-selector-.md new file mode 100644 index 0000000000..d2656b8071 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-not-selector-.md @@ -0,0 +1,62 @@ +--- +title: 'Selection.not(selector)' +excerpt: 'Remove elements from the set of matched elements.' +--- + +Remove elements from the set of matched elements. +Mimics [jquery.not](https://api.jquery.com/not/) + +| Parameter | Type | Description | +| --------- | -------- | -------------------------------------------------------------------- | +| selector | string | A string containing a selector expression to match elements against. | +| selector | function | A function used as a test for each element in the set. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + let sel = doc.find('dl').children(); + + console.log(sel.not('dt').size()); + + sel = sel.not(function (idx, item) { + return item.text().startsWith('definition'); + }); + + console.log(sel.size()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-parent--selector--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-parent--selector--.md new file mode 100644 index 0000000000..b14a87cca1 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-parent--selector--.md @@ -0,0 +1,47 @@ +--- +title: 'Selection.parent([selector])' +excerpt: 'Get the parent of each element in the current set of matched elements, optionally filtered by a selector.' +--- + +Get the parent of each element in the current set of matched elements, optionally filtered by a selector. +Mimics [jquery.parent](https://api.jquery.com/parent/). + +| Parameter | Type | Description | +| ------------------- | ------ | -------------------------------------------------------------------- | +| selector (optional) | string | A string containing a selector expression to match elements against. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` + + `; + const doc = parseHTML(content); + + const sel = doc.find('li.third-item').parent(); + + console.log(sel.html()); + + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-parents--selector--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-parents--selector--.md new file mode 100644 index 0000000000..ab572727ec --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-parents--selector--.md @@ -0,0 +1,47 @@ +--- +title: 'Selection.parents([selector])' +excerpt: 'Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.' +--- + +Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. +Mimics [jquery.parents](https://api.jquery.com/parents/). + +| Parameter | Type | Description | +| ------------------- | ------ | -------------------------------------------------------------------- | +| selector (optional) | string | A string containing a selector expression to match elements against. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` + + `; + const doc = parseHTML(content); + + const sel = doc.find('li.third-item').parents(); + + console.log(sel.size()); + + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-parentsUntil-selector-filter.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-parentsUntil-selector-filter.md new file mode 100644 index 0000000000..d46c56dd78 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-parentsUntil-selector-filter.md @@ -0,0 +1,59 @@ +--- +title: 'Selection.parentsUntil([selector], [filter])' +excerpt: 'Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.' +--- + +Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector. +Mimics [jquery.parentsUntil](https://api.jquery.com/parentsUntil/) + +| Parameter | Type | Description | +| ------------------- | ------------------------------------------------------------------ | ---------------------------------------------------------- | +| selector (optional) | string \| [Selection](/javascript-api/v0-31/k6-html/selection) \| `null` | A selector expression or object to match elements against. | +| filter (optional) | string \| `null` | A selector expression to filter matched elements. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + const sel = doc.find('#term-2').parentsUntil('dt'); + console.log(sel.size()); + + const selFilter = doc.find('#term-3').parentsUntil('dt', 'dd'); + console.log(selFilter.size()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-prev--selector--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-prev--selector--.md new file mode 100644 index 0000000000..a816fcbe59 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-prev--selector--.md @@ -0,0 +1,46 @@ +--- +title: 'Selection.prev([selector])' +excerpt: 'Get the immediately preceding sibling of each element in the set of matched elements.' +--- + +Get the immediately preceding sibling of each element in the set of matched elements. +Mimics [jquery.prev](https://api.jquery.com/prev/). + +| Parameter | Type | Description | +| ------------------- | ------ | -------------------------------------------------------------------- | +| selector (optional) | string | A string containing a selector expression to match elements against. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` + + `; + const doc = parseHTML(content); + const sel = doc.find('li.third-item').prev(); + + console.log(sel.html()); + + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-prevAll--selector--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-prevAll--selector--.md new file mode 100644 index 0000000000..76aa610df6 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-prevAll--selector--.md @@ -0,0 +1,47 @@ +--- +title: 'Selection.prevAll([selector])' +excerpt: 'Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.' +--- + +Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. +Mimics [jquery.prevAll](https://api.jquery.com/prevAll/). + +| Parameter | Type | Description | +| ------------------- | ------ | -------------------------------------------------------------------- | +| selector (optional) | string | A string containing a selector expression to match elements against. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` + + `; + const doc = parseHTML(content); + + const sel = doc.find('li.third-item').prevAll(); + + console.log(sel.size()); + + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-prevUntil-selector-filter.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-prevUntil-selector-filter.md new file mode 100644 index 0000000000..8d482500be --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-prevUntil-selector-filter.md @@ -0,0 +1,59 @@ +--- +title: 'Selection.prevUntil([selector], [filter])' +excerpt: 'Get all preceding siblings of each element up to but not including the element matched by the selector.' +--- + +Get all preceding siblings of each element up to but not including the element matched by the selector. +Mimics [jquery.prevUntil](https://api.jquery.com/prevUntil/). + +| Parameter | Type | Description | +| ------------------- | ------------------------------------------------------------------ | ---------------------------------------------------------- | +| selector (optional) | string \| [Selection](/javascript-api/v0-31/k6-html/selection) \| `null` | A selector expression or object to match elements against. | +| filter (optional) | string \| `null` | A selector expression to filter matched elements. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + const sel = doc.find('#term-2').prevUntil('dt'); + console.log(sel.size()); + + const selFilter = doc.find('#term-3').prevUntil('#term-1', 'dd'); + console.log(selFilter.size()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-serialize--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-serialize--.md new file mode 100644 index 0000000000..f4f078960a --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-serialize--.md @@ -0,0 +1,38 @@ +--- +title: 'Selection.serialize()' +excerpt: 'Encode a set of form elements as a string in standard URL-encoded notation for submission.' +--- + +Encode a set of form elements as a string in standard URL-encoded notation for submission. +Mimics [jquery.serialize](https://api.jquery.com/serialize/) + +### Returns + +| Type | Description | +| ------ | -------------------------------------------------------------------- | +| string | The URL-encoded representation of the matched form or form elements. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+ `; + + const doc = parseHTML(content); + const sel = doc.find('form'); + const serialized = sel.serialize(); + + console.log(serialized); // "username=" + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-serializeArray--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-serializeArray--.md new file mode 100644 index 0000000000..aff61485b7 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-serializeArray--.md @@ -0,0 +1,38 @@ +--- +title: 'Selection.serializeArray()' +excerpt: 'Encode a set of form elements as an array of names and values.' +--- + +Encode a set of form elements as an array of names and values (`[{ name: "name", value: "value" }, ...]`). +Mimics [jquery.serializeArray](https://api.jquery.com/serializeArray/) + +### Returns + +| Type | Description | +| ----- | --------------------------------------------------------------- | +| array | Array of names and values of the matched form or form elements. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+ `; + + const doc = parseHTML(content); + const sel = doc.find('form'); + const serialized = sel.serializeArray(); + + console.log(JSON.stringify(serialized)); // [{"name": "username", "value": ""}] + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-serializeObject--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-serializeObject--.md new file mode 100644 index 0000000000..88b07e20a1 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-serializeObject--.md @@ -0,0 +1,37 @@ +--- +title: 'Selection.serializeObject()' +excerpt: 'Encode a set of form elements as an object.' +--- + +Encode a set of form elements as an object (`{ "inputName": "value", "checkboxName": "value" }`). + +### Returns + +| Type | Description | +| ------ | ------------------------------------------------------------------------------------------------------- | +| object | Object representation of the matched form or form elements, key is field name and value is field value. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+ `; + + const doc = parseHTML(content); + const sel = doc.find('form'); + const serialized = sel.serializeObject(); + + console.log(JSON.stringify(serialized)); // {"username": ""} + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-size--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-size--.md new file mode 100644 index 0000000000..fbc6e517b8 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-size--.md @@ -0,0 +1,52 @@ +--- +title: 'Selection.size()' +excerpt: 'Return the number of elements in the Selection.' +--- + +Return the number of elements in the Selection. +Mimics [jquery.size](https://api.jquery.com/size/) + +### Returns + +| Type | Description | +| ------ | ---------------------------------------- | +| Number | The number of elements in the Selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + const sel = doc.find('dt'); + + console.log(sel.size()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-slice-start -- end--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-slice-start -- end--.md new file mode 100644 index 0000000000..b34194c259 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-slice-start -- end--.md @@ -0,0 +1,60 @@ +--- +title: 'Selection.slice(start [, end])' +excerpt: 'Reduce the set of matched elements to a subset specified by a range of indices.' +--- + +Reduce the set of matched elements to a subset specified by a range of indices. +Mimics [jquery.slice](https://api.jquery.com/slice/) + +| Parameter | Type | Description | +| --------- | ---------------------------------------------- | -------------------------------------------------------------------------------------- | +| start | Number | An integer indicating the 0-based position at which the elements begin to be selected. | +| end | Number | An integer indicating the 0-based position at which the elements stop being selected. | +| selector | [Selection](/javascript-api/v0-31/k6-html/selection) | A selection. | + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | The new selection. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + const els = doc.find('dl').children(); + + console.log(els.slice(4).text()); + + console.log(els.slice(2, 4).text()); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-text--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-text--.md new file mode 100644 index 0000000000..be18769bc6 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-text--.md @@ -0,0 +1,30 @@ +--- +title: 'Selection.text()' +excerpt: 'Get the text content of the Selection.' +--- + +Get the text content of the Selection. +Mimics [jquery.text](https://api.jquery.com/text/). + +### Returns + +| Type | Description | +| ------ | ----------------------- | +| string | Selection text content. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import http from 'k6/http'; + +export default function () { + const res = http.get('https://k6.io'); + const doc = parseHTML(res.body); + const pageTitle = doc.find('head title').text(); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-toArray--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-toArray--.md new file mode 100644 index 0000000000..b96f6d48fc --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-toArray--.md @@ -0,0 +1,56 @@ +--- +title: 'Selection.toArray()' +excerpt: 'Retrieve all the elements contained in the Selection, as an array.' +--- + +Retrieve all the elements contained in the Selection, as an array. +Mimics [jquery.toArray](https://api.jquery.com/toArray/). + +### Returns + +| Type | Description | +| ------------------------------------------------------- | --------------------------- | +| Array of [Selection](/javascript-api/v0-31/k6-html/selection) | Array of Selection objects. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` +
+
term 1
+
definition 1-a
+
definition 1-b
+
definition 1-c
+
definition 1-d
+ +
term 2
+
definition 2-a
+
definition 2-b
+
definition 2-c
+ +
term 3
+
definition 3-a
+
definition 3-b
+
+ `; + const doc = parseHTML(content); + + doc + .find('dl') + .children() + .toArray() + .forEach(function (item) { + console.log(item.text()); + }); + + sleep(1); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-val--.md b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-val--.md new file mode 100644 index 0000000000..2478ccc840 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/06 k6-html/50 Selection/Selection-val--.md @@ -0,0 +1,54 @@ +--- +title: 'Selection.val()' +excerpt: 'Get the current value of the first element in the set of matched elements.' +--- + +Get the current value of the first element in the set of matched elements. +Mimics [jquery.val](https://api.jquery.com/val/). + +### Returns + +| Type | Description | +| ------ | -------------------------------------------------------------- | +| string | The value of the first element in the set of matched elements. | + +### Example + + + +```javascript +import { parseHTML } from 'k6/html'; +import { sleep } from 'k6'; + +export default function () { + const content = ` + + + + + + `; + const doc = parseHTML(content); + + console.log(doc.find('#text_input').val()); + console.log(doc.find('#select_one option[selected]').val()); + console.log(doc.find('#select_one').val()); + console.log(doc.find('#select_text').val()); + console.log(doc.find('#select_multi').val()); + console.log(doc.find('#textarea').val()); + + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http.md new file mode 100644 index 0000000000..ab5d4244e9 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http.md @@ -0,0 +1,28 @@ +--- +title: 'k6/http' +excerpt: 'The k6/http module contains functionality for performing HTTP transactions.' +--- + +The k6/http module contains functionality for performing HTTP transactions. + +| Function | Description | +| -------- | ----------- | +| [batch( requests )](/javascript-api/v0-31/k6-http/batch-requests) | Issue multiple HTTP requests in parallel (like e.g. browsers tend to do). | +| [cookieJar()](/javascript-api/v0-31/k6-http/cookiejar-method) | Get active HTTP Cookie jar. | +| [del( url, [body], [params] )](/javascript-api/v0-31/k6-http/del-url-body-params) | Issue an HTTP DELETE request. | +| [file( data, [filename], [contentType] )](/javascript-api/v0-31/k6-http/file-data-filename-contenttype) | Create a file object that is used for building multi-part requests. | +| [get( url, [params] )](/javascript-api/v0-31/k6-http/get-url-params) | Issue an HTTP GET request. | +| [options( url, [body], [params] )](/javascript-api/v0-31/k6-http/options-url-body-params) | Issue an HTTP OPTIONS request. | +| [patch( url, [body], [params] )](/javascript-api/v0-31/k6-http/patch-url-body-params) | Issue an HTTP PATCH request. | +| [post( url, [body], [params] )](/javascript-api/v0-31/k6-http/post-url-body-params) | Issue an HTTP POST request. | +| [put( url, [body], [params] )](/javascript-api/v0-31/k6-http/put-url-body-params) | Issue an HTTP PUT request. | +| [request( method, url, [body], [params] )](/javascript-api/v0-31/k6-http/request-method-url-body-params) | Issue any type of HTTP request. | +| [setResponseCallback(expectedStatuses)](/javascript-api/v0-31/k6-http/setresponsecallback-callback) | Sets a response callback to mark responses as expected. | +| [expectedStatuses( statusCodes )](/javascript-api/v0-31/k6-http/expectedstatuses-statuses) | Create a callback for setResponseCallback that checks status codes. | + +| Class | Description | +| -------- | ----------- | +| [CookieJar](/javascript-api/v0-31/k6-http/cookiejar) | Used for storing cookies, set by the server and/or added by the client. | +| [FileData](/javascript-api/v0-31/k6-http/filedata) | Used for wrapping data representing a file when doing multipart requests (file uploads). | +| [Params](/javascript-api/v0-31/k6-http/params) | Used for setting various HTTP request-specific parameters such as headers, cookies, etc. | +| [Response](/javascript-api/v0-31/k6-http/response) | Returned by the http.* methods that generate HTTP requests. | diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-batch- requests -.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-batch- requests -.md new file mode 100644 index 0000000000..880bdd2735 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-batch- requests -.md @@ -0,0 +1,152 @@ +--- +title: 'batch( requests )' +description: 'Issue multiple HTTP requests in parallel (like e.g. browsers tend to do).' +excerpt: 'Issue multiple HTTP requests in parallel (like e.g. browsers tend to do).' +--- + +Batch multiple HTTP requests together, to issue them in parallel over multiple TCP connections. + +| Parameter | Type | Description | +| --------- | --------------- | ---------------------------------------------------------------- | +| requests | array \| object | An array or object containing requests, in string or object form | + +When each request is specified as an array, the order of the arguments for each request is as follows: + +### Returns + +| Type | Description | +| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| object | An object containing [Response](/javascript-api/v0-31/k6-http/response) objects.

It is an array when users pass an array as `requests` and is a normal object with string keys when named requests are used (see below). | + +| Position | Name | Type | Description | +| -------- | ----------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------- | +| 1 | method | string | Mandatory. The HTTP method of the request. One of GET, POST, PUT, PATCH, DELETE, HEAD or OPTION. | +| 2 | url | string | Mandatory. The URL to request. | +| 3 | body (optional) | string / object / ArrayBuffer | The body of the request if relevant. Can be set to `null` if not applicable but you want to set the last `params` argument. | +| 4 | params (optional) | object | [Params](/javascript-api/v0-31/k6-http/params) like auth, custom headers and tags. | + +### Example with request as an array + + + +```javascript +import http from 'k6/http'; +import { check } from 'k6'; + +export default function () { + let responses = http.batch([ + ['GET', 'https://test.k6.io', null, { tags: { ctype: 'html' } }], + ['GET', 'https://test.k6.io/style.css', null, { tags: { ctype: 'css' } }], + [ + 'GET', + 'https://test.k6.io/images/logo.png', + null, + { tags: { ctype: 'images' } }, + ], + ]); + check(responses[0], { + 'main page status was 200': (res) => res.status === 200, + }); +} +``` + + + +### Example batching three URLs for parallel fetching + + + +```javascript +import http from 'k6/http'; +import { check } from 'k6'; + +export default function () { + let responses = http.batch([ + ['GET', 'https://test.k6.io', null, { tags: { ctype: 'html' } }], + ['GET', 'https://test.k6.io/style.css', null, { tags: { ctype: 'css' } }], + [ + 'GET', + 'https://test.k6.io/images/logo.png', + null, + { tags: { ctype: 'images' } }, + ], + ]); + check(responses[0], { + 'main page status was 200': (res) => res.status === 200, + }); +} +``` + + + +### Example with request objects + +You can also use objects to hold information about a request. Here is an example where we do that in order to send a POST request, plus use custom HTTP headers by adding a [Params](/javascript-api/v0-31/k6-http/params) object to the request: + + + +```javascript +import http from 'k6/http'; +import { check } from 'k6'; + +export default function () { + let req1 = { + method: 'GET', + url: 'https://httpbin.org/get', + }; + let req2 = { + method: 'GET', + url: 'https://test.k6.io', + }; + let req3 = { + method: 'POST', + url: 'https://httpbin.org/post', + body: { + hello: 'world!', + }, + params: { + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + }, + }; + let responses = http.batch([req1, req2, req3]); + // httpbin.org should return our POST data in the response body, so + // we check the third response object to see that the POST worked. + check(responses[2], { + 'form data OK': (res) => JSON.parse(res.body)['form']['hello'] == 'world!', + }); +} +``` + + + +_Note that the requests in the example above may happen in any order, or simultaneously. When running requests in batches, there is no guarantee that e.g. req1 will happen before req2 or req3_ + +### Example with named requests + +Finally, you can also send in named requests by using an object instead of an array as the parameter to http.batch(). In the following example we do this, and we also show that it is possible to mix string URLs and request objects + + + +```javascript +import http from 'k6/http'; +import { check } from 'k6'; + +export default function () { + let requests = { + 'front page': 'https://k6.io', + 'features page': { + method: 'GET', + url: 'https://k6.io/features', + params: { headers: { 'User-Agent': 'k6' } }, + }, + }; + let responses = http.batch(requests); + // when accessing results, we use the name of the request as index + // in order to find the corresponding Response object + check(responses['front page'], { + 'front page status was 200': (res) => res.status === 200, + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-cookieJar--.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-cookieJar--.md new file mode 100644 index 0000000000..85b2221bda --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-cookieJar--.md @@ -0,0 +1,26 @@ +--- +title: 'cookieJar()' +slug: '/javascript-api/v0-31/k6-http/cookiejar-method' +description: 'Get active HTTP Cookie jar.' +excerpt: 'Get active HTTP Cookie jar.' +--- + +Get the active cookie jar. + +| Type | Description | +| ---------------------------------------------- | ------------------- | +| [CookieJar](/javascript-api/v0-31/k6-http/cookiejar) | A CookieJar object. | + +### Example + + + +```javascript +import http from 'k6/http'; + +export default function () { + let jar = http.cookieJar(); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-del- url- -body-- -params- -.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-del- url- -body-- -params- -.md new file mode 100644 index 0000000000..f31049ffa2 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-del- url- -body-- -params- -.md @@ -0,0 +1,36 @@ +--- +title: 'del( url, [body], [params] )' +description: 'Issue an HTTP DELETE request.' +excerpt: 'Issue an HTTP DELETE request.' +--- + +Make a DELETE request. + +| Parameter | Type | Description | +| ---------------------------- | --------------- | ----------------------------------------------------------------------------------------- | +| url | string | Request URL (e.g. `http://example.com`). | +| body (optional, discouraged) | string / object / ArrayBuffer | Request body; objects will be `x-www-form-urlencoded`. This is discouraged, because sending a DELETE request with a body has [no defined semantics](https://tools.ietf.org/html/rfc7231#section-4.3.5) and may cause some servers to reject it. | +| params (optional) | object | [Params](/javascript-api/v0-31/k6-http/params) object containing additional request parameters. | + +### Returns + +| Type | Description | +| -------- | --------------------------------------------------------- | +| Response | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + +### Example + + + +```javascript +import http from 'k6/http'; + +const url = 'https://httpbin.test.k6.io/delete'; + +export default function () { + let params = { headers: { 'X-MyHeader': 'k6test' } }; + http.del(url, null, params); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-file- data- -filename-- -contentType- -.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-file- data- -filename-- -contentType- -.md new file mode 100644 index 0000000000..6cffd7ce78 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-file- data- -filename-- -contentType- -.md @@ -0,0 +1,40 @@ +--- +title: 'file( data, [filename], [contentType] )' +description: 'Create a file object that is used for building multi-part requests.' +excerpt: 'Create a file object that is used for building multi-part requests.' +--- + +Create a file object that is used for building [Multipart requests (file uploads)](/examples/data-uploads#multipart-request-uploading-a-file). + +| Parameter | Type | Description | +| ----------- | ---------------------------- | -------------------------------------------------------------------------------- | +| data | string / Array / ArrayBuffer (≥ v0.31.0) | File data as string, array of numbers, or an `ArrayBuffer` object. | +| filename | string | The filename to specify for this field (or "part") of the multipart request. | +| contentType | string | The content type to specify for this field (or "part") of the multipart request. | + +### Returns + +| Type | Description | +| -------------------------------------------- | ------------------ | +| [FileData](/javascript-api/v0-31/k6-http/filedata) | A FileData object. | + +### Example + + + +```javascript +import { sleep } from 'k6'; +import { md5 } from 'k6/crypto'; +import http from 'k6/http'; + +let binFile = open('/path/to/file.bin', 'b'); + +export default function () { + let f = http.file(binFile, 'test.bin'); + console.log(md5(f.data, 'hex')); + console.log(f.filename); + console.log(f.content_type); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-get- url- -params- -.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-get- url- -params- -.md new file mode 100644 index 0000000000..0280425eb6 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-get- url- -params- -.md @@ -0,0 +1,33 @@ +--- +title: 'get( url, [params] )' +description: 'Issue an HTTP GET request.' +excerpt: 'Issue an HTTP GET request.' +--- + +Make a GET request. + +| Parameter | Type | Description | +| ----------------- | ------ | ----------------------------------------------------------------------------------------- | +| url | string | Request URL (e.g. `http://example.com`). | +| params (optional) | object | [Params](/javascript-api/v0-31/k6-http/params) object containing additional request parameters. | + +### Returns + +| Type | Description | +| -------------------------------------------- | --------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | HTTP Response object. | + +### Example fetching a URL + + + +```javascript +import http from 'k6/http'; + +export default function () { + let res = http.get('https://k6.io'); + console.log(JSON.stringify(res.headers)); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-options- url- -body-- -params- -.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-options- url- -body-- -params- -.md new file mode 100644 index 0000000000..44602c6a0c --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-options- url- -body-- -params- -.md @@ -0,0 +1,37 @@ +--- +title: "options( url, [body], [params] )" +description: "Issue an HTTP OPTIONS request." +excerpt: "Issue an HTTP OPTIONS request." +--- + +| Parameter | Type | Description | +| ----------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------- | +| url | string | Request URL (e.g. `http://example.com`). | +| body (optional) | string / object / ArrayBuffer | Request body; objects will be `x-www-form-urlencoded`. | +| params (optional) | object | [Params](/javascript-api/v0-31/k6-http/params) object containing additional request parameters. | + + +### Returns + +| Type | Description | +| -------- | --------------------------------------------------------------------- | +| Response | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + + +### Example + + + +```javascript +import http from 'k6/http'; + +const url = 'https://httpbin.test.k6.io/'; + +export default function () { + let params = { headers: { 'X-MyHeader': 'k6test' } }; + let res = http.options(url, null, params); + console.log(res.headers['Allow']); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-patch- url- -body-- -params- -.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-patch- url- -body-- -params- -.md new file mode 100644 index 0000000000..fb880c272c --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-patch- url- -body-- -params- -.md @@ -0,0 +1,38 @@ +--- +title: 'patch( url, [body], [params] )' +description: 'Issue an HTTP PATCH request.' +excerpt: 'Issue an HTTP PATCH request.' +--- + +| Parameter | Type | Description | +| ----------------- | ----------------------------- | ---------------------------------------------------------------------------------------- | +| url | string | Request URL (e.g. `http://example.com`). | +| body (optional) | string / object / ArrayBuffer | Request body; objects will be `x-www-form-urlencoded`. | +| params (optional) | object | [Params](/javascript-api/v0-31/k6-http/params) object containing additional request parameters | + +### Returns + +| Type | Description | +| -------------------------------------------- | --------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | HTTP Response object. | + +### Example + + + +```javascript +import http from 'k6/http'; + +const url = 'https://httpbin.test.k6.io/patch'; + +export default function () { + const headers = { 'Content-Type': 'application/json' }; + const data = { name: 'Bert' }; + + let res = http.patch(url, JSON.stringify(data), { headers: headers }); + + console.log(JSON.parse(res.body).json.name); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-post- url- -body-- -params- -.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-post- url- -body-- -params- -.md new file mode 100644 index 0000000000..108d01d3a9 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-post- url- -body-- -params- -.md @@ -0,0 +1,53 @@ +--- +title: 'post( url, [body], [params] )' +description: 'Issue an HTTP POST request.' +excerpt: 'Issue an HTTP POST request.' +--- + +| Parameter | Type | Description | +| ------------------- | ----------------------------- | ---------------------------------------------------------------------------------------- | +| `url` | string | Request URL (e.g. `http://example.com`). | +| `body` | string / object / ArrayBuffer | Request body; objects will be `x-www-form-urlencoded`. | +| `params` (optional) | object | [Params](/javascript-api/v0-31/k6-http/params) object containing additional request parameters | + +### Returns + +| Type | Description | +| ---------- | --------------------------------------------------------- | +| `Response` | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + +### Example + + + +```javascript +import http from 'k6/http'; + +const url = 'https://httpbin.test.k6.io/post'; +const logoBin = open('./logo.png', 'b'); + +export default function () { + let data = { name: 'Bert' }; + + // Using a JSON string as body + let res = http.post(url, JSON.stringify(data), + { headers: { 'Content-Type': 'application/json' } }); + console.log(res.json().json.name); // Bert + + // Using an object as body, the headers will automatically include + // 'Content-Type: application/x-www-form-urlencoded'. + res = http.post(url, data); + console.log(res.json().form.name); // Bert + + // Using a binary array as body. Make sure to open() the file as binary + // (with the 'b' argument). + http.post(url, logoBin, { headers: { 'Content-Type': 'image/png' }}); + + // Using an ArrayBuffer as body. Make sure to pass the underlying ArrayBuffer + // instance to http.post(), and not the TypedArray view. + data = new Uint8Array([104, 101, 108, 108, 111]); + http.post(url, data.buffer, { headers: { 'Content-Type': 'image/png' }}); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-put- url- -body-- -params- -.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-put- url- -body-- -params- -.md new file mode 100644 index 0000000000..939ec6f86a --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-put- url- -body-- -params- -.md @@ -0,0 +1,38 @@ +--- +title: 'put( url, [body], [params] )' +description: 'Issue an HTTP PUT request.' +excerpt: 'Issue an HTTP PUT request.' +--- + +| Parameter | Type | Description | +| ----------------- | ----------------------------- | ----------------------------------------------------------------------------------------- | +| url | string | Request URL (e.g. `http://example.com`). | +| body (optional) | string / object / ArrayBuffer | Request body; objects will be `x-www-form-urlencoded`. | +| params (optional) | object | [Params](/javascript-api/v0-31/k6-http/params) object containing additional request parameters. | + +### Returns + +| Type | Description | +| -------- | --------------------------------------------------------- | +| Response | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + +### Example + + + +```javascript +import http from 'k6/http'; + +const url = 'https://httpbin.test.k6.io/put'; + +export default function () { + const headers = { 'Content-Type': 'application/json' }; + const data = { name: 'Bert' }; + + let res = http.put(url, JSON.stringify(data), { headers: headers }); + + console.log(JSON.parse(res.body).json.name); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-request- method- url- -body-- -params- -.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-request- method- url- -body-- -params- -.md new file mode 100644 index 0000000000..a2bad9f35d --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-request- method- url- -body-- -params- -.md @@ -0,0 +1,46 @@ +--- +title: 'request( method, url, [body], [params] )' +description: 'Issue any type of HTTP request.' +excerpt: 'Issue any type of HTTP request.' +--- + +| Parameter | Type | Description | +| ----------------- | ----------------------------- | ----------------------------------------------------------------------------------------- | +| method | string | Request method (e.g. `POST`). Note, the method must be uppercase. | +| url | string | Request URL (e.g. `http://example.com`). | +| body (optional) | string / object / ArrayBuffer | Request body; objects will be `x-www-form-urlencoded`. | +| params (optional) | object | [Params](/javascript-api/v0-31/k6-http/params) object containing additional request parameters. | + +### Returns + +| Type | Description | +| -------- | --------------------------------------------------------- | +| Response | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + +### Example + +Using http.request() to issue a POST request: + + + +```javascript +import http from 'k6/http'; + +const url = 'https://httpbin.test.k6.io/post'; + +export default function () { + let data = { name: 'Bert' }; + + // Using a JSON string as body + let res = http.request('POST', url, JSON.stringify(data), + { headers: { 'Content-Type': 'application/json' } }); + console.log(res.json().json.name); // Bert + + // Using an object as body, the headers will automatically include + // 'Content-Type: application/x-www-form-urlencoded'. + res = http.request('POST', url, data); + console.log(res.json().form.name); // Bert +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-set-response-callback-expectedStatuses.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-set-response-callback-expectedStatuses.md new file mode 100644 index 0000000000..ff28d60ad3 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/10-set-response-callback-expectedStatuses.md @@ -0,0 +1,54 @@ +--- +title: 'setResponseCallback( callback )' +description: 'set responseCallback to mark responses as expected' +excerpt: 'set responseCallback to mark responses as expected' +--- + +> ### 🎉 New in v0.31.0 + +Set the response callback to be called to determine if a response was expected/successful or not. + +The result of this is that requests will be tagged with `expected_response` `"true"` or `"false"` and `http_req_failed` will be emitted with the reverse. This does include all redirects so if for a request only 200 is the expected response and there is 301 redirect before that, the redirect will be marked as failed as only status code 200 was marked as expected. + +#### Exceptions + +Due to implementation specifics: +- Requests with authentication `digest` are always expected to first get 401 and then to get whatever was specified. +- Requests with authentication `ntlm` will let a 401 status code on the first request as well as anything defined by `expectedStatuses` + + +| Parameter | Type | Description | +| --------- | --------------- | ---------------------------------------------------------------- | +| callback | [expectedStatuses](/javascript-api/v0-31/k6-http/expectedstatuses-statuses) | an object returned from [expectedStatuses](/javascript-api/v0-31/k6-http/expectedstatuses-statuses) | + +Currently only the very special [expectedStatuses](/javascript-api/v0-31/k6-http/expectedstatuses-statuses) objects are supported but in the future it is planned that a JavaScript callback will be supported as well. By default requests with status codes between 200 and 399 are considered "expected". + +Setting the callback to `null` disables the tagging with `expected_response` and the emitting of `http_req_failed`, effectively reverting to the behaviour prior to v0.31.0. + +It is recommended that if a per request responseCallback is used with [Params](/javascript-api/v0-31/k6-http/params) it is actually defined once and used instead of creating it on each request. + +### Example + + + +```javascript +import http from 'k6/http'; + +http.setResponseCallback(http.expectedStatuses({min: 200, max: 300})); + +var only300Callback = http.expectedStatuses(300); + +export default () => { + // this will use the default response callback and be marked as successful + http.get("https://httpbin.test.k6.io/status/200"); + + // this will be marked as a failed request as it won't get the expected status code of 300 + http.get("https://httpbin.test.k6.io/status/200", {responseCallback: only300Callback}); + + http.setResponseCallback(http.expectedStatuses(301)); + // from here on for this VU only the 301 status code will be successful so on the next iteration of + // the VU the first request will be marked as failure +}; +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/11-expected-statuses.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/11-expected-statuses.md new file mode 100644 index 0000000000..a48eccb5e3 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/11-expected-statuses.md @@ -0,0 +1,35 @@ +--- +title: 'expectedStatuses( statuses )' +description: 'generates a responseCallback to check status codes' +excerpt: 'generates a responseCallback to check status codes' +--- + +> ### 🎉 New in v0.31.0 + +Returns a callback to be used with [setResponseCallback](/javascript-api/v0-31/k6-http/setresponsecallback-callback) to mark responses as expected based only on their status codes. + + +| Parameter | Type | Description | +| --------- | --------------- | ---------------------------------------------------------------- | +| statuses | integer/objects | either an integer or an object like {min:100, max:300} which gives a minimum and maximum expected status codes| + +You can have as many arguments as wanted in any order. + +### Example + + + +```javascript +import http from 'k6/http'; + +// setting some pretty strange status codes as expected +http.setResponseCallback(http.expectedStatuses(406, 500, {min: 200, max: 204}, 302, {min: 305, max: 405})); + +export default () => { + // this one will actually be marked as failed as it doesn't match any of the above listed status + // codes + http.get("https://httpbin.test.k6.io/status/205"); +}; +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60 CookieJar.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60 CookieJar.md new file mode 100644 index 0000000000..5df83408d6 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60 CookieJar.md @@ -0,0 +1,37 @@ +--- +title: 'CookieJar' +head_title: 'CookieJar object' +description: 'Used for storing cookies, set by the server and/or added by the client.' +excerpt: 'Used for storing cookies, set by the server and/or added by the client.' +--- + +_CookieJar_ is an object for storing cookies, set by the server and/or added by the client. As described in the how-to guide on using [Cookies](/using-k6/cookies), k6 handles cookies automatically by default. If you need more control over cookies you can however create your own cookie jar and select it as the active jar (instead of the default one created by k6) for one or more requests. + +| Method | Description | +| ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | +| [cookiesForURL(url)](/javascript-api/v0-31/k6-http/cookiejar/cookiejar-cookiesforurl-url) | Get Object of cookies where the key is the cookie name and the value is an array. | +| [set(url, name, value, [options])](/javascript-api/v0-31/k6-http/cookiejar/cookiejar-set-url-name-value-options) | Set a cookie in the jar by specifying name, value and some other optional settings like domain, path etc. | + +### Example + + + +```javascript +import http from 'k6/http'; +import { check } from 'k6'; + +export default function () { + let res = http.get( + 'https://httpbin.org/cookies/set?my_cookie=hello%20world', + { redirects: 0 }, + ); + let jar = http.cookieJar(); + let cookies = jar.cookiesForURL('http://httpbin.org/'); + check(res, { + "has cookie 'my_cookie'": (r) => cookies.my_cookie.length > 0, + 'cookie has correct value': (r) => cookies.my_cookie[0] === 'hello world', + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60 CookieJar/CookieJar-cookiesForUrl-url.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60 CookieJar/CookieJar-cookiesForUrl-url.md new file mode 100644 index 0000000000..13b4b61869 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60 CookieJar/CookieJar-cookiesForUrl-url.md @@ -0,0 +1,38 @@ +--- +title: 'CookieJar.cookiesForURL(url)' +excerpt: 'Get bbject of cookies where the key is the cookie name and the value is an array.' +--- + +| Parameter | Type | Description | +| --------- | ------ | --------------------------------- | +| url | string | The URL for which to get cookies. | + +### Returns + +| Type | Description | +| ------ | ----------------------------------------------------------------------------- | +| object | Object of cookies where the key is the cookie name and the value is an array. | + +### Example + + + +```javascript +import http from 'k6/http'; +import { check } from 'k6'; + +export default function () { + let res = http.get( + 'https://httpbin.org/cookies/set?my_cookie=hello%20world', + { redirects: 0 }, + ); + let jar = http.cookieJar(); + let cookies = jar.cookiesForURL('http://httpbin.org/'); + check(res, { + "has cookie 'my_cookie'": (r) => cookies.my_cookie.length > 0, + 'cookie has correct value': (r) => cookies.my_cookie[0] === 'hello world', + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60 CookieJar/CookieJar-set-url-name-value-options.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60 CookieJar/CookieJar-set-url-name-value-options.md new file mode 100644 index 0000000000..dff37940b6 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60 CookieJar/CookieJar-set-url-name-value-options.md @@ -0,0 +1,41 @@ +--- +title: 'CookieJar.set(url, name, value, [options])' +excerpt: 'Set a cookie in the jar by specifying url, name, value and some other optional settings like domain, path, etc.' +--- + +Set a cookie in the jar by specifying url, name, value and some other optional settings like domain, path, etc. + +| Parameter | Type | Description | +| ------------------ | ------ | ------------------------------------------------------------------------------------------- | +| url | string | Cookie URL | +| name | string | Cookie name | +| value | string | Cookie value | +| options (optional) | object | Specific cookie settings: `domain`, `path`, `expires`, `max_age`, `secure` and `http_only`. | + +### Example + + + +```javascript +import http from 'k6/http'; +import { check } from 'k6'; + +export default function () { + let jar = http.cookieJar(); + jar.set('https://httpbin.org/cookies', 'my_cookie', 'hello world', { + domain: 'httpbin.org', + path: '/cookies', + secure: true, + max_age: 600, + }); + let res = http.get('https://httpbin.org/cookies'); + check(res, { + 'has status 200': (r) => r.status === 200, + "has cookie 'my_cookie'": (r) => r.json().cookies.my_cookie !== null, + 'cookie has correct value': (r) => + r.json().cookies.my_cookie == 'hello world', + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60-FileData.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60-FileData.md new file mode 100644 index 0000000000..c4d0894108 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60-FileData.md @@ -0,0 +1,36 @@ +--- +title: 'FileData' +description: 'Used for wrapping data representing a file when doing multipart requests (file uploads).' +excerpt: 'Used for wrapping data representing a file when doing multipart requests (file uploads).' +--- + +_FileData_ is an object for wrapping data representing a file when doing +[multipart requests (file uploads)](/examples/data-uploads#multipart-request-uploading-a-file). +You create it by calling [http.file( data, [filename], [contentType] )](/javascript-api/v0-31/k6-http/file-data-filename-contenttype). + +| Name | Type | Description | +| --------------------- | ---------------------------- | ------------------------------------------------------------------------ | +| FileData.data | string / Array / ArrayBuffer (≥ v0.31.0) | File data as string, array of numbers, or an `ArrayBuffer` object. | +| FileData.content_type | string | The content type that will be specified in the multipart request. | +| FileData.filename | string | The filename that will be specified in the multipart request. | + +### Example + + + +```javascript +import { sleep } from 'k6'; +import { md5 } from 'k6/crypto'; +import http from 'k6/http'; + +let binFile = open('/path/to/file.bin', 'b'); + +export default function () { + let f = http.file(binFile, 'test.bin'); + console.log(md5(f.data, 'hex')); + console.log(f.filename); + console.log(f.content_type); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60-Params.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60-Params.md new file mode 100644 index 0000000000..c72b50c9c5 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/60-Params.md @@ -0,0 +1,120 @@ +--- +title: 'Params' +description: 'Used for setting various HTTP request-specific parameters such as headers, cookies, etc.' +excerpt: 'Used for setting various HTTP request-specific parameters such as headers, cookies, etc.' +--- + +_Params_ is an object used by the http.\* methods that generate HTTP requests. _Params_ contains request-specific options like e.g. HTTP headers that should be inserted into the request. + +| Name | Type | Description | +| --------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Params.auth` | string | The authentication method used for the request. It currently supports `digest`, `ntlm`, and `basic` authentication methods. | +| `Params.cookies` | object | Object with key-value pairs representing request scoped cookies (they won't be added to VU cookie jar)
`{cookies: { key: "val", key2: "val2" }}`

You also have the option to say that a request scoped cookie should override a cookie in the VU cookie jar:
`{cookies: { key: { value: "val", replace: true }}}` | +| `Params.headers` | object | Object with key-value pairs representing custom HTTP headers the user would like to add to the request. | +| `Params.jar` | object | http.CookieJar object to override default VU cookie jar with. Cookies added to request will be sourced from this jar and cookies set by server will be added to this jar. | +| `Params.redirects` | number | The number of redirects to follow for this request. Overrides the global test option [`maxRedirects`](/using-k6/options). | +| `Params.tags` | object | Key-value pairs where the keys are names of tags and the values are tag values. Response time metrics generated as a result of the request will have these tags added to them, allowing the user to filter out those results specifically, when looking at results data. | +| `Params.timeout` | string / number | Maximum time to wait for the request to complete. Default timeout is 60 seconds (`"60s"`).
Since version 0.30, `timeout` accepts a string type. For backward compatibility, the type can also be a number, in which case k6 interprets it as milliseconds, e.g., `60000` is equivalent to `"60s"`. | +| `Params.compression` | string | Sets whether the request body should be compressed. If set to `gzip` it will use gzip to compress the body and set the appropriate `Content-Length` and `Content-Encoding` headers.

Possible values: `gzip`, `deflate`, `br`, `zstd`, and any comma-separated combination of them (for stacked compression) | +| `Params.responseType` | string | ResponseType is used to specify how to treat the body of the response. The three options are:
- text: k6 will return it as a string. This might not be what you want in cases of binary data as the conversation to UTF-16 will probably break it. This is also the default if
[discardResponseBodies](/using-k6/options) is set to false or not set at all.
- `binary`: k6 will return an array of ints/bytes
- `none`: k6 will return null as the body. The whole body will be ignored. This is the default when [discardResponseBodies](/using-k6/options) is set to true. | +| `Params.responseCallback` | [expectedStatuses](/javascript-api/v0-31/k6-http/expectedstatuses-statuses) | sets a [responseCallback](/javascript-api/v0-31/k6-http/setresponsecallback-callback) only for this request. For performance reasons it's better to initialize it once and reference it for each time the same callback will need to be used| + +### Example of custom HTTP headers and tags + +_A k6 script that will make an HTTP request with a custom HTTP header and tag results data with a specific tag_ + + + +```javascript +import http from 'k6/http'; + +export default function () { + let params = { + cookies: { my_cookie: 'value' }, + headers: { 'X-MyHeader': 'k6test' }, + redirects: 5, + tags: { k6test: 'yes' }, + }; + let res = http.get('https://k6.io', params); +} +``` + + + +### Example using http.batch() with Params + +Here is another example using [http.batch()](/javascript-api/v0-31/k6-http/batch-requests) with a `Params` argument: + + + +```javascript +import http from 'k6/http'; + +let url1 = 'https://api.k6.io/v3/account/me'; +let url2 = 'http://httpbin.org/get'; +let apiToken = + 'f232831bda15dd233c53b9c548732c0197619a3d3c451134d9abded7eb5bb195'; +let requestHeaders = { + 'User-Agent': 'k6', + Authorization: 'Token ' + apiToken, +}; + +export default function () { + let res = http.batch([ + { method: 'GET', url: url1, params: { headers: requestHeaders } }, + { method: 'GET', url: url2 }, + ]); +} +``` + + + +### Example of Digest Authentication + +Here is one example of how to use the `Params` to Digest Authentication. + + + +```javascript +import http from 'k6/http'; +import { check } from 'k6'; + +export default function () { + // Passing username and password as part of URL plus the auth option will authenticate using HTTP Digest authentication + let res = http.get( + 'http://user:passwd@httpbin.org/digest-auth/auth/user/passwd', + { auth: 'digest' }, + ); + + // Verify response + check(res, { + 'status is 200': (r) => r.status === 200, + 'is authenticated': (r) => r.json().authenticated === true, + 'is correct user': (r) => r.json().user === 'user', + }); +} +``` + + +Example how to overwrite discardResponseBodies: + +### Example of overwrite discardResponseBodies + + + +```javascript +import http from 'k6/http'; + +export var options = { discardResponseBodies: true }; +export default function () {} +export function setup() { + // Get 10 random bytes in as an array of ints/bytes, without the responseType the body will be null + const response = http.get('https://httpbin.org/bytes/10', { + responseType: 'binary', + }); + // Print the array. Will look something like `176,61,15,66,233,98,223,196,43,1` + console.log(response.body); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response.md new file mode 100644 index 0000000000..18a4d41c74 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response.md @@ -0,0 +1,75 @@ +--- +title: 'Response' +description: 'Returned by the http.* methods that generate HTTP requests.' +excerpt: 'Returned by the http.* methods that generate HTTP requests.' +--- + +Response is used by the http.\* methods that generate HTTP request. Those methods return one (or more, in the case of `http.batch()`) Response objects that contain HTTP response contents and performance timing measurements. + +Note that in the case of redirects, all the information in the Response object will pertain to the last request (the one that doesn't get redirected). + +| Name | Type | Description | +| ---------------------------------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Response.body` | string | Response body content.

See [Params.responseType](/javascript-api/v0-31/k6-http/params) and [options.discardResponseBodies](/using-k6/options) for how to discard the body when it's not needed (and to save memory) or when handling bodies with binary data. | +| `Response.cookies` | object | Response cookies. The object properties are the cookie names and the value is an array of cookie objects (with `name`, `value`, `domain`, `path`, `httpOnly`, `secure`, `maxAge` and `expires` fields). | +| `Response.error` | string | Error message if there was a non-HTTP error while trying to send the request. | +| `Response.error_code` | number | [Error code](/javascript-api/v0-31/error-codes) if there was a non-HTTP error or 4xx or 5xx HTTP error it will be set to a specific code that describes the error. (Added in 0.24.0) | +| `Response.headers` | object | Key-value pairs representing all HTTP headers sent by the server. | +| `Response.ocsp.produced_at` | number | If a stapled OSCP response was provided by server, the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC, representing the time when this OCSP stapled response was signed by CA (or by CA entrusted OCSP responder) | +| `Response.ocsp.this_update` | number | If a stapled OSCP response was provided by server, the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC, representing the time at which the status being indicated was known to be correct. | +| `Response.ocsp.next_update` | number | If a stapled OSCP response was provided by server, the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC, representing the time when this OCSP stapled response will be refreshed with CA (or by CA entrusted OCSP responder). | +| `Response.ocsp.revocation_reason` | string | The reason for revocation of the certificate (if that is the status), one of the following constants: `http.OCSP_REASON_UNSPECIFIED`, `http.OCSP_REASON_KEY_COMPROMISE`, `http.OCSP_REASON_CA_COMPROMISE`,
`http.OCSP_REASON_AFFILIATION_CHANGED`,
`http.OCSP_REASON_SUPERSEDED`,
`http.OCSP_REASON_CESSATION_OF_OPERATION`,
`http.OCSP_REASON_CERTIFICATE_HOLD`,
`http.OCSP_REASON_REMOVE_FROM_CRL`,
`http.OCSP_REASON_PRIVILEGE_WITHDRAWN` or
`http.OCSP_REASON_AA_COMPROMISE`. | +| `Response.ocsp.revoked_at` | number | If a stapled OSCP response was provided by server, the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC, representing the time when this certificate was revoked (if that is the status). | +| `Response.ocsp.status` | string | The status of the certificate, one of the following constants: `http.OCSP_STATUS_GOOD`, `http.OCSP_STATUS_REVOKED`, `http.OCSP_STATUS_UNKNOWN` or `http.OCSP_STATUS_SERVER_FAILED`. | +| `Response.proto` | string | Protocol used to perform the transfer. Possible values are "HTTP/1.0", "HTTP/1.1", or "HTTP/2.0". | +| `Response.remote_ip` | string | The IP address of the server handling the request. | +| `Response.remote_port` | number | The port that was connected to on the server side. | +| `Response.request.body` | string | Request body content. | +| `Response.request.cookies` | object | Request cookies. The object properties are the cookie names and the value is an array of cookie objects (with `name`, `value` and `replace` fields). | +| `Response.request.headers` | object | Request headers. | +| `Response.request.method` | string | Request HTTP method. | +| `Response.request.url` | string | Request URL. | +| `Response.status` | number | HTTP status code returned by the server. | +| `Response.status_text` | string | _(new in k6 v0.29.0)_ HTTP status text returned by the server. | +| `Response.timings` | object | Performance timing information for the HTTP request. | +| `Response.timings.blocked` | float | Containing time (ms) spent blocked before initiating request. | +| `Response.timings.looking_up` (currently unavailable) | float | Containing time (ms) spent looking up host name in DNS. | +| `Response.timings.connecting` | float | Containing time (ms) spent setting up TCP connection to host. | +| `Response.timings.tls_handshaking` | float | Containing time (ms) spent handshaking TLS session with host. | +| `Response.timings.sending` | float | Containing time (ms) spent sending request. | +| `Response.timings.waiting` | float | Containing time (ms) spent waiting for server response. | +| `Response.timings.receiving` | float | Containing time (ms) spent receiving response data. | +| `Response.timings.duration` | float | Total time for the request (ms). It's equal to `sending + waiting + receiving`, i.e. how long did the remote server take to process the request and respond, without the initial DNS lookup/connection times. | +| `Response.tls_cipher_suite` | string | If a TLS session was established, the cipher suite that was used. | +| `Response.tls_version` | string | If a TLS session was established, the version of SSL/TLS that was used. | +| `Response.url` | string | The URL that was ultimately fetched (i.e. after any potential redirects). | +| [Response.clickLink( [params] )](/javascript-api/v0-31/k6-http/response/response-clicklink-params) | function | Parses response as HTML, looks for a specific link and does the request-level equivalent of a click on that link. | +| [Response.html()](/javascript-api/v0-31/k6-http/response/response-html) | function | Returns an object that supports [Selection.find(selector)](/javascript-api/v0-31/k6-html/selection/selection-find-selector). | +| [Response.json( [selector] )](/javascript-api/v0-31/k6-http/response/response-json-selector) | function | Parses the response body data as JSON and returns a JS object or array. This call caches the deserialized JSON data, additional calls will return the cached data. An optional selector can be specified to extract a specific part of the data, see [here for selector syntax](https://github.com/tidwall/gjson#path-syntax). | +| [Response.submitForm( [params] )](/javascript-api/v0-31/k6-http/response/response-submitform-params) | function | Parses response as HTML, parses the specified form (defaults to looking for a "form" element) with option to override fields and then submits form taking form's `method` and `action` into account. | + +### Example + + + +```javascript +import { check } from 'k6'; +import http from 'k6/http'; + +export default function () { + let res = http.get('https://k6.io'); + for (var p in res.headers) { + if (res.headers.hasOwnProperty(p)) { + console.log(p + ' : ' + res.headers[p]); + } + } + check(res, { + 'status is 200': (r) => r.status === 200, + 'caption is correct': (r) => r.html('h1').text() == 'Example Domain', + }); +} +``` + + + +_A k6 script that will make an HTTP request and print all HTTP response headers_ diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response/Response-clickLink- -params- -.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response/Response-clickLink- -params- -.md new file mode 100644 index 0000000000..20f351c8fa --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response/Response-clickLink- -params- -.md @@ -0,0 +1,37 @@ +--- +title: 'Response.clickLink( [params] )' +excerpt: 'Create and make a request corresponding to a link, found in the HTML of response, being clicked.' +--- + +Create and make a request corresponding to a link, found in the HTML of response, being clicked. By default it will look for the first `a` tag with a `href` attribute in the HTML, but this can be overridden using the `selector` option. + +This method takes an object argument where the following properties can be set: + +| Param | Type | Description | +| -------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| selector | string | A selector string passed to [Selection.find(selector)](/javascript-api/v0-31/k6-html/selection/selection-find-selector) to locate the link to click. By default this is `"a[href]"`. | +| params | object | A [Params](/javascript-api/v0-31/k6-http/params) object that will be forwarded to the link click request. Can be used to set headers, cookies etc. | + +### Returns + +| Type | Description | +| -------------------------------------------- | ----------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | The link click response | + +### Example + + + +```javascript +import http from 'k6/http'; + +export default function () { + // Request page with links + let res = http.get('https://httpbin.org/links/10/0'); + + // Now, click the 4th link on the page + res = res.clickLink({ selector: 'a:nth-child(4)' }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response/Response-html--.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response/Response-html--.md new file mode 100644 index 0000000000..95c333a37a --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response/Response-html--.md @@ -0,0 +1,34 @@ +--- +title: 'Response.html()' +excerpt: 'Parses response as HTML and populate a Selection.' +--- + +Parses response as HTML and populate a [Selection](/javascript-api/v0-31/k6-html/selection) object. + +### Returns + +| Type | Description | +| ---------------------------------------------- | ------------------ | +| [Selection](/javascript-api/v0-31/k6-html/selection) | A Selection object | + +### Example + + + +```javascript +import http from 'k6/http'; + +export default function () { + let res = http.get('https://stackoverflow.com'); + + let doc = res.html(); + doc + .find('link') + .toArray() + .forEach(function (item) { + console.log(item.attr('href')); + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response/Response-json- -selector- -.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response/Response-json- -selector- -.md new file mode 100644 index 0000000000..1f78212876 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response/Response-json- -selector- -.md @@ -0,0 +1,34 @@ +--- +title: 'Response.json( [selector] )' +excerpt: 'Parses the response body data as JSON and returns a JS object or array.' +--- + +Parses the response body data as JSON and returns a JS object or array. This call caches the deserialized JSON data, additional calls will return the cached data. An optional selector can be specified to extract a specific part of the data, see [here for selector syntax](https://github.com/tidwall/gjson#path-syntax). + +This method takes an object argument where the following properties can be set: + +| Param | Type | Description | +| -------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| selector | string | An optional selector can be specified to extract a specific part of the data, see [here for selector syntax](https://github.com/tidwall/gjson#path-syntax). | + +### Returns + +| Type | Description | +| --------------- | ----------------------------------------- | +| Object or array | Returns the response body as JSON object. | + +### Example + + + +```javascript +import http from 'k6/http'; + +export default function () { + let res = http.get('https://test-api.k6.io/public/crocodiles/') + + console.log(res.json()); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response/Response-submitForm- -params- -.md b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response/Response-submitForm- -params- -.md new file mode 100644 index 0000000000..11ba511300 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/07 k6-http/61 Response/Response-submitForm- -params- -.md @@ -0,0 +1,44 @@ +--- +title: 'Response.submitForm( [params] )' +excerpt: 'Fill in and submit form found in HTML of response.' +--- + +Fill in and submit form found in HTML of response. By default it will look for the first `form` tag in the HTML, but this can be overridden using the `formSelector` option. To set/override the form fields you set properties of an object in the `fields` option. + +This method takes an object argument where the following properties can be set: + +| Param | Type | Description | +| -------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| formSelector | string | A selector string passed to [Selection.find(selector)](/javascript-api/v0-31/k6-html/selection/selection-find-selector) to locate the form to fill in and submit. By default this is `"form"`. | +| fields | object | The form fields to set/override. The keys are the form fields names and the values are the form field values. | +| submitSelector | string | A selector string used to locate the submit button in the form. By default this is `'[type="submit"]'`. | +| params | object | A [Params (k6/http)](/javascript-api/v0-31/k6-http/params) object that will be forwarded to the form submit request. Can be used to set headers, cookies etc. | + +### Returns + +| Type | Description | +| ------------------------------------------------------ | ------------------------- | +| [Response (k6/http)](/javascript-api/v0-31/k6-http/response) | The form submit response. | + +### Example + + + +```javascript +import http from 'k6/http'; +import { sleep } from 'k6'; + +export default function () { + // Request page containing a form + let res = http.get('https://httpbin.org/forms/post'); + + // Now, submit form setting/overriding some fields of the form + res = res.submitForm({ + formSelector: 'form', + fields: { custname: 'test', extradata: 'test2' }, + }); + sleep(3); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics.md b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics.md new file mode 100644 index 0000000000..c136d9063f --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics.md @@ -0,0 +1,15 @@ +--- +title: 'k6/metrics' +excerpt: 'k6 Custom Metrics API' +--- + +The metrics module provides functionality to create [custom metrics](/using-k6/metrics) of various types. All metrics (both the [built-in metrics](/using-k6/metrics#built-in-metrics) and the custom ones) have a type. + +All values added to a custom metric can optionally be [tagged](/using-k6/tags-and-groups) which can be useful when analysing the test results. + +| Metric type | Description | +| --------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| [Counter](/javascript-api/v0-31/k6-metrics/counter) | A metric that cumulatively sums added values. | +| [Gauge](/javascript-api/v0-31/k6-metrics/gauge) | A metric that stores the min, max and last values added to it. | +| [Rate](/javascript-api/v0-31/k6-metrics/rate) | A metric that tracks the percentage of added values that are non-zero. | +| [Trend](/javascript-api/v0-31/k6-metrics/trend) | A metric that allows for calculating statistics on the added values (min, max, average and percentiles). | diff --git a/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/70 Counter.md b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/70 Counter.md new file mode 100644 index 0000000000..8a01075fe6 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/70 Counter.md @@ -0,0 +1,99 @@ +--- +title: 'Counter' +excerpt: 'Counter is an object for representing a custom cumulative counter metric. It is one of the four custom metric types.' +--- + +_Counter_ is an object for representing a custom cumulative counter metric. It is one of the four custom metric types. + +| Parameter | Type | Description | +| --------- | ------ | ------------------------------ | +| `name` | string | The name of the custom metric. | + +| Method | Description | +| --------------------------------------------------------------------------------------- | ---------------------------------- | +| [Counter.add(value, [tags])](/javascript-api/v0-31/k6-metrics/counter/counter-add-value-tags) | Add a value to the counter metric. | + +## Counter usage in Thresholds + +When `Counter` is used in a threshold expression, the variable must be called `count` or `rate` (lower case). +For example: + +- `count >= 200` // value of the counter must be larger or equal to 200 +- `count < 10` // less than 10. + +### Examples + + + +```javascript +import { Counter } from 'k6/metrics'; + +var myCounter = new Counter('my_counter'); + +export default function() { + myCounter.add(1); + myCounter.add(2, { tag1: 'myValue', tag2: 'myValue2' }); +} +``` + + + + + +```javascript +import http from "k6/http"; +import { Counter } from "k6/metrics"; + +let CounterErrors = new Counter("Errors"); + +export let options = { thresholds: { "Errors": ["count<100"] } }; + +export default function() { + let res = http.get('https://test-api.k6.io/public/crocodiles/1/'); + let contentOK = res.json("name") === 'Bert'; + CounterErrors.add(!contentOK); +}; +``` + + + + + +```javascript +import { Counter } from 'k6/metrics'; +import { sleep } from 'k6'; +import http from 'k6/http'; + +let allErrors = new Counter('error_counter'); + +export let options = { + vus: 1, + duration: '1m', + thresholds: { + 'error_counter': [ + 'count < 10', // 10 or fewer total errors are tolerated + ], + 'error_counter{errorType:authError}': [ // Threshold on a sub-metric (tagged values) + 'count <= 2', // max 2 authentication errors are tolerated + ] + } +}; + +export default function () { + let auth_resp = http.post('https://test-api.k6.io/auth/token/login/', + {username: 'test-user', 'password': 'supersecure'}); + + if (auth_resp.status >= 400){ + allErrors.add(1, { errorType: 'authError' }); // tagged value creates submetric (useful for making thresholds specific) + } + + let other_resp = http.get('https://test-api.k6.io/public/crocodiles/1/'); + if (other_resp.status >= 400) { + allErrors.add(1); // untagged value + } + + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/70 Counter/Counter-add-value- -tags--.md b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/70 Counter/Counter-add-value- -tags--.md new file mode 100644 index 0000000000..bf1b1c4f3e --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/70 Counter/Counter-add-value- -tags--.md @@ -0,0 +1,14 @@ +--- +title: "Counter.add(value, [tags])" +excerpt: 'Add a value to the Counter metric.' +--- + +Add a value to the `Counter` metric. + +| Parameter | Type | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| value | number | The value to add to the counter. | +| tags | object | Set of [tags](/using-k6/tags-and-groups) that will be tagged to the added data point (note that tags are added per data point and not for the entire metric). | + + +[Counter examples](/javascript-api/v0-31/k6-metrics/counter#examples) diff --git a/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/71 Gauge.md b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/71 Gauge.md new file mode 100644 index 0000000000..305a6b35b9 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/71 Gauge.md @@ -0,0 +1,65 @@ +--- +title: 'Gauge' +excerpt: 'Gauge is an object for representing a custom metric holding only the latest value added.' +--- + +_Gauge_ is an object for representing a custom metric holding only the latest value added. It is one of the four [custom metrics](/javascript-api/v0-31/k6-metrics). + +| Parameter | Type | Description | +| --------- | ------- | --------------------------------------------------------------------------------------------------- | +| `name` | string | The name of the custom metric. | +| `isTime` | boolean | A boolean indicating whether the values added to the metric are time values or just untyped values. | + +| Method | Description | +| --------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | +| [Gauge.add(value, [tags])](/javascript-api/v0-31/k6-metrics/gauge/gauge-add-value-tags) | Add a value to the gauge metric. Only the latest value added will be kept. | + +## Gauge usage in Thresholds + +When gauge is used in a threshold expression, the variable must be called `value` (lower case). +For example: + +- `value < 200` +- `value > 1` + +### Examples + + + +```javascript +import { Gauge } from 'k6/metrics'; + +var myGauge = new Gauge('my_gauge'); + +export default function () { + myGauge.add(3); + myGauge.add(1); + myGauge.add(2, { tag1: 'value', tag2: 'value2' }); +} +``` + + + + + +```javascript +import http from 'k6/http'; +import { sleep } from 'k6'; +import { Gauge } from 'k6/metrics'; + +let GaugeContentSize = new Gauge('ContentSize'); + +export let options = { + thresholds: { + ContentSize: ['value<4000'], + }, +}; + +export default function () { + let res = http.get('https://test-api.k6.io/public/crocodiles/1/'); + GaugeContentSize.add(res.body.length); + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/71 Gauge/Gauge-add-value- -tags--.md b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/71 Gauge/Gauge-add-value- -tags--.md new file mode 100644 index 0000000000..2315c2e5ce --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/71 Gauge/Gauge-add-value- -tags--.md @@ -0,0 +1,13 @@ +--- +title: "Gauge.add(value, [tags])" +excerpt: 'Set the value of the Gauge metric.' +--- + +Set the value of the `Gauge` metric. + +| Parameter | Type | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| value | number | The value to set the gauge to. | +| tags | object | Set of [tags](/using-k6/tags-and-groups) that will be tagged to the added data point (note that tags are added per data point and not for the entire metric). | + +[Gauge examples](/javascript-api/v0-31/k6-metrics/gauge#examples) diff --git a/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/72 Rate.md b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/72 Rate.md new file mode 100644 index 0000000000..1e5b104641 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/72 Rate.md @@ -0,0 +1,74 @@ +--- +title: 'Rate' +excerpt: 'Rate is an object for representing a custom metric keeping track of the percentage of added values that are non-zero.' +--- + +_Rate_ is an object for representing a custom metric keeping track of the percentage of added values that are non-zero. It is one of the four [custom metrics](/javascript-api/v0-31/k6-metrics). + +| Parameter | Type | Description | +| --------- | ------ | ------------------------------ | +| `name` | string | The name of the custom metric. | + +| Method | Description | +| -------------------------------------------------------------------------------- | ------------------------------- | +| [Rate.add(value, [tags])](/javascript-api/v0-31/k6-metrics/rate/rate-add-value-tags) ] | Add a value to the rate metric. | + +## Rate usage in Thresholds + +When `Rate` is used in a threshold expression, the variable must be called `rate` (lower case). +For example: + +- `rate < 0.1` // less than 10% +- `rate >= 0.9` // more or equal to 90% + +The value of the `rate` variable ranges between `0.00` and `1.00`. + +### Examples + + + +```javascript +import { Rate } from 'k6/metrics'; + +var myRate = new Rate('my_rate'); + +export default function() { + myRate.add(true); + myRate.add(false); + myRate.add(1); + myRate.add(0, { tag1: 'value', tag2: 'value2' }); +} +``` + + + + + +```javascript +import { Rate } from 'k6/metrics'; +import { sleep } from 'k6'; +import http from 'k6/http'; + +let errorRate = new Rate('errorRate'); + +export let options = { + vus: 1, + duration: '5m', + thresholds: { + 'errorRate': [ + // more than 10% of errors will abort the test + { threshold: 'rate < 0.1', abortOnFail: true, delayAbortEval: '1m' } + ] + } +}; + +export default function () { + let resp = http.get('https://test-api.k6.io/public/crocodiles/1/'); + + errorRate.add(resp.status >= 400); + + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/72 Rate/Rate-add-value- -tags--.md b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/72 Rate/Rate-add-value- -tags--.md new file mode 100644 index 0000000000..45f1ba96bd --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/72 Rate/Rate-add-value- -tags--.md @@ -0,0 +1,13 @@ +--- +title: "Rate.add(value, [tags])" +excerpt: 'Set the value of the Rate metric.' +--- + +Set the value of the `Rate` metric. + +| Parameter | Type | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| value | number | The value to add to the rate metric. | +| tags | object | Set of [tags](/using-k6/tags-and-groups) that will be tagged to the added data point (note that tags are added per data point and not for the entire metric). | + +[Rate examples](/javascript-api/v0-31/k6-metrics/rate#examples) diff --git a/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/73 Trend.md b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/73 Trend.md new file mode 100644 index 0000000000..bbc239d64f --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/73 Trend.md @@ -0,0 +1,86 @@ +--- +title: 'Trend' +excerpt: 'Trend is an object for representing a custom metric that allows for calculating different statistics on the added values (min, max, average or percentiles)' +--- + +_Trend_ is an object for representing a custom metric that allows for calculating different statistics on the added values (min, max, average or percentiles). It is one of the four [custom metrics](/javascript-api/v0-31/k6-metrics). + +| Parameter | Type | Description | +| --------- | ------- | --------------------------------------------------------------------------------------------------- | +| `name` | string | The name of the custom metric. | +| `isTime` | boolean | A boolean indicating whether the values added to the metric are time values or just untyped values. | + +| Method | Description | +| --------------------------------------------------------------------------------- | -------------------------------- | +| [Trend.add(value, [tags])](/javascript-api/v0-31/k6-metrics/trend/trend-add-value-tags) | Add a value to the trend metric. | + +## Trend usage in Thresholds + +When `Trend` is used in a [threshold expression](/using-k6/thresholds), there are a range of variables that can be used. + +- `avg` for average +- `min` for minimum +- `max` for maximum +- `med` for median +- `p(N)` for specific percentile. `N` is a number between `0.0` and `100.0` meaning the percentile value to look at, e.g. `p(99.99)` means the 99.99th percentile. + +The unit of these variables and functions are all in milliseconds. + +### Example threshold expressions: + +- `p(95) < 400` // 95% of requests must finish below 400ms +- `p(99) < 1000` // 99% of requests must finish within 1s. +- `p(50) < 200` // half of requests must finish within 200ms. +- `max < 3000` // the slowest request must finish within 3s. + + +> #### ⚠️ Don't use `min` and `max` in thresholds +> We don't recommend using `min` and `max` for specifying thresholds because these +> values represent outliers. Use percentiles instead. + + +### Examples + + + +```javascript +import { Trend } from 'k6/metrics'; + +var myTrend = new Trend('my_trend'); + +export default function() { + myTrend.add(1); + myTrend.add(2, { tag1: 'value', tag2: 'value2' }); +} +``` + + + + + +```javascript +import { Trend } from 'k6/metrics'; +import { sleep } from 'k6'; +import http from 'k6/http'; + +let serverWaitingTimeOnLogin = new Trend('serverWaitingTimeOnLogin', true); + +export let options = { + vus: 1, + duration: '1m', + thresholds: { + 'serverWaitingTimeOnLogin': [ + 'p(95) < 200', + ], + } +}; + +export default function () { + let resp = http.post('https://test-api.k6.io/auth/token/login/', { username: 'test-user', 'password': 'supersecure' }); + + serverWaitingTimeOnLogin.add(resp.timings.waiting); + sleep(1); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/73 Trend/Trend-add-value- -tags--.md b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/73 Trend/Trend-add-value- -tags--.md new file mode 100644 index 0000000000..361950b983 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/08 k6-metrics/73 Trend/Trend-add-value- -tags--.md @@ -0,0 +1,14 @@ +--- +title: "Trend.add(value, [tags])" +excerpt: 'Add a value to the Trend metric.' +--- + +Add a value to the `Trend` metric. + +| Parameter | Type | Description | +| --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| value | number | The value to add to the trend metric. | +| tags | object | Set of [tags](/using-k6/tags-and-groups) that will be tagged to the added data point (note that tags are added per data point and not for the entire metric). | + + +[Trend examples](/javascript-api/v0-31/k6-metrics/trend#examples) \ No newline at end of file diff --git a/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc.md b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc.md new file mode 100644 index 0000000000..41d6cfa262 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc.md @@ -0,0 +1,55 @@ +--- +title: "k6/net/grpc" +excerpt: "k6 gRPC API" +--- + +The `k6/net/grpc` module, added in k6 v0.29.0, provides a [gRPC](https://grpc.io/) client for Remote Procedure Calls (RPC) over HTTP/2. + +
+ +The k6 gRPC API is currently considered in beta and is subject to change. Future k6 versions might have slight differences in the method and type signatures described in this documentation. + +
+ +| Class/Method | Description | +|--------------|-------------| +| [Client](/javascript-api/v0-31/k6-net-grpc/client) | gRPC client used for making RPC calls to a gRPC Server. | +| [Client.load(importPaths, ...protoFiles)](/javascript-api/v0-31/k6-net-grpc/client/client-load-importpaths----protofiles) | Loads and parses the given protocol buffer definitions to be made available for RPC requests. | +| [Client.connect(address [,params])](/javascript-api/v0-31/k6-net-grpc/client/client-connect-address-params) | Connects to a given gRPC service. | +| [Client.invoke(url, request [,params])](/javascript-api/v0-31/k6-net-grpc/client/client-invoke-url-request-params) | Makes an unary RPC for the given service/method and returns a [Response](/javascript-api/v0-31/k6-net-grpc/response). | +| [Client.close()](/javascript-api/v0-31/k6-net-grpc/client/client-close) | Close the connection to the gRPC service. | +| [Params](/javascript-api/v0-31/k6-net-grpc/params) | RPC Request specific options. | +| [Response](/javascript-api/v0-31/k6-net-grpc/response) | Returned by RPC requests. | +| [Constants](/javascript-api/v0-31/k6-net-grpc/constants) | Define constants to distinguish between [gRPC Response](/javascript-api/v0-31/k6-net-grpc/response) statuses. | + +### Example + + + +```javascript +import grpc from 'k6/net/grpc'; +import { check, sleep } from 'k6'; + +const client = new grpc.Client(); +client.load(['definitions'], 'hello.proto'); + +export default () => { + client.connect('grpcb.in:9001', { + // plaintext: false + }); + + const data = { greeting: 'Bert' }; + const response = client.invoke('hello.HelloService/SayHello', data); + + check(response, { + 'status is OK': (r) => r && r.status === grpc.StatusOK, + }); + + console.log(JSON.stringify(response.message)); + + client.close(); + sleep(1); +}; +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/10-Client.md b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/10-Client.md new file mode 100644 index 0000000000..df945581e8 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/10-Client.md @@ -0,0 +1,102 @@ +--- +title: Client +excerpt: 'Client is a gRPC client that can interact with a gRPC server.' +--- + +`Client` is a gRPC client that can interact with a gRPC server. + +> ⚠️ **Note**: Only unary RPCs are currently supported, i.e. there is no support for client, server or bidirectional streaming. + +| Method | Description | +|--------|-------------| +| [Client.load(importPaths, ...protoFiles)](/javascript-api/v0-31/k6-net-grpc/client/client-load-importpaths----protofiles) | Loads and parses the given protocol buffer definitions to be made available for RPC requests. | +| [Client.connect(address [,params])](/javascript-api/v0-31/k6-net-grpc/client/client-connect-address-params) | Opens a connection to the given gRPC server. | +| [Client.invoke(url, request [,params])](/javascript-api/v0-31/k6-net-grpc/client/client-invoke-url-request-params) | Makes an unary RPC for the given service/method and returns a [Response](/javascript-api/v0-31/k6-net-grpc/response). | +| [Client.close()](/javascript-api/v0-31/k6-net-grpc/client/client-close) | Close the connection to the gRPC service. | + + +### Examples + +
+ +```javascript +import grpc from "k6/net/grpc"; + +let client = new grpc.Client(); +// Download addsvc.proto for https://grpcb.in/, located at: +// https://raw.githubusercontent.com/moul/pb/master/addsvc/addsvc.proto +// and put it in the same folder as this script. +client.load(null, "addsvc.proto"); + +export default () => { + client.connect("grpcb.in:9001", { timeout: "5s" }); + + let response = client.invoke("addsvc.Add/Sum", { + a: 1, + b: 2 + }); + console.log(response.message.v); // should print 3 + + client.close(); +} +``` + +
+ +
+ +```javascript +import grpc from "k6/net/grpc"; +import { check } from "k6"; + +const client = new grpc.Client(); +client.load([], "authorization.proto", "route_guide.proto"); + +export function setup() { + client.connect("auth.googleapis.com:443"); + const resp = client.invoke("google.cloud.authorization.v1.AuthService/GetAccessToken", { + username: "john.smith@k6.io", + password: "its-a-secret", + }); + client.close(); + return resp.message.accessToken; + +} + +export default (token) => { + client.connect("route.googleapis.com:443"); + const headers = { + authorization: `bearer ${token}`, + }; + const response = client.invoke("google.cloud.route.v1.RoutingService/GetFeature", { + latitude: 410248224, + longitude: -747127767 + + }, { headers }); + check(response, { "status is OK": (r) => r && r.status === grpc.StatusOK }); + client.close(); +} +``` + +
+ +
+ +```javascript +import grpc from "k6/net/grpc"; +import { check } from "k6"; + +const client = new grpc.Client(); +client.load([], "language_service.proto"); + +export default () => { + if (__ITER == 0) { + client.connect("language.googleapis.com:443"); + } + const response = client.invoke("google.cloud.language.v1.LanguageService/AnalyzeSentiment", {}); + check(response, { "status is OK": (r) => r && r.status === grpc.StatusOK }); + // Do NOT close the client +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20 Client/10-Client-load-importpaths-protoFiles.md b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20 Client/10-Client-load-importpaths-protoFiles.md new file mode 100644 index 0000000000..8380f174b2 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20 Client/10-Client-load-importpaths-protoFiles.md @@ -0,0 +1,42 @@ +--- +title: "Client.load(importPaths, ...protoFiles)" +excerpt: 'Loads and parses the protocol buffer descriptors so they are available to the client to marshal/unmarshal the correct request and response data structures for the RPC schema.' +--- + +Loads and parses the protocol buffer descriptors so they are available to the client to marshal/unmarshal the correct request and response data structures for the RPC schema. + +Must be called within the [`init` phase](/using-k6/test-life-cycle). + +| Parameter | Type | Description | +|-----------|------|-------------| +| importPaths | Array<string> \| `null` | The paths used to search for dependencies that are referenced in import statements in proto source files. If no import paths are provided then "." (current directory) is assumed to be the only import path. | +| protoFiles | Array<string> | [Rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) for the list of proto files to load/parse. | + +### Examples + +
+ +```javascript +import grpc from "k6/net/grpc"; + +const client = new grpc.Client(); +client.load([], "language_service.proto"); +``` + +
+ +
+ +```javascript +import grpc from "k6/net/grpc"; + +const client = new grpc.Client(); +client.load( + ["../googleapis/google"], + "spanner/admin/instance/v1/spanner_instance_admin.proto", + "spanner/admin/database/v1/spanner_database_admin.proto", + "spanner/v1/spanner.proto", +); +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20 Client/20-Client-connect-connect-address-params.md b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20 Client/20-Client-connect-connect-address-params.md new file mode 100644 index 0000000000..8d9e3f3c17 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20 Client/20-Client-connect-connect-address-params.md @@ -0,0 +1,49 @@ +--- +title: "Client.connect(address [,params])" +excerpt: 'Opens a connection to a gRPC server; will block until a connection is made or a connection error is thrown.' +--- + +Opens a connection to a gRPC server; will block until a connection is made or a connection error is thrown. Cannot be called during the [`init` phase](/using-k6/test-life-cycle). + +See [Client.close()](/javascript-api/v0-31/k6-net-grpc/client/client-close) to close the connection. + +| Parameter | Type | Description | +|-----------|------|-------------| +| address | string | The address of the gRPC server. Should be in the form: `host:port` with no protocol prefix e.g. `grpc.k6.io:443`. The host must be a literal IP address, or a host name that can be resolved to IP addresses. The port must be a literal port number or a service name e.g. `:443` or `:https`. If the host is a literal IPv6 address it must be enclosed in square brackets, as in `[2001:db8::1]:80` or `[fe80::1%zone]:80`. | +| params (optional) | object | [ConnectParams](#connectparams) object containing additional connect parameters. | + + +## ConnectParams + +| Name | Type | Description | +|------|------|-------------| +| `ConnectParams.plaintext` | bool | If `true` will connect to the gRPC server using plaintext i.e. insecure. Defaults to `false` i.e. secure via TLS. | +| `ConnectParams.timeout` | number | Connection timeout to use. Default timeout is `"60s"` (60 seconds). | + +### Examples + +
+ +```javascript +import grpc from "k6/net/grpc"; + +const client = new grpc.Client(); + +export default () => { + client.connect("localhost:8080"); +} +``` +
+ +
+ +```javascript +import grpc from "k6/net/grpc"; + +const client = new grpc.Client(); + +export default () => { + client.connect("localhost:8080", { plaintext: true }); +} +``` +
diff --git a/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20 Client/30-Client-invokerpc-url-request-params.md b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20 Client/30-Client-invokerpc-url-request-params.md new file mode 100644 index 0000000000..f0d5516b01 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20 Client/30-Client-invokerpc-url-request-params.md @@ -0,0 +1,51 @@ +--- +title: "Client.invoke(url, request [,params])" +excerpt: 'Invokes an unary RPC request to the given method.' +--- + +Invokes an unary RPC request to the given method. + +The given method to invoke must have its RPC schema previously loaded via the [Client.load()](/javascript-api/v0-31/k6-net-grpc/client/client-load-importpaths----protofiles) function, otherwise an +error will be thrown. + +[Client.connect()](/javascript-api/v0-31/k6-net-grpc/client/client-connect-address-params) must be called first before invoking a request, otherwise an error will be thrown. + +| Parameter | Type | Description | +|-----------|------|-------------| +| url | string | The gRPC method url to invoke, in the form `/package.Service/Method`, e.g. `/google.cloud.language.v1.LanguageService/AnalyzeSentiment`. The leading slash `/` is optional. | +| request | object | The canonical request object, as-per the [Protobuf JSON Mapping](https://developers.google.com/protocol-buffers/docs/proto3#json). | +| params (optional) | object | [Params](/javascript-api/v0-31/k6-net-grpc/params) object containing additional request parameters. + +### Returns + +| Type | Description | +|------|-------------| +| `Response` | gRPC [Response](/javascript-api/v0-31/k6-net-grpc/response) object. | + +### Examples + +
+ +```javascript +import grpc from "k6/net/grpc"; +import { check } from "k6"; + +const client = new grpc.Client(); +client.load([], "routeguide.proto"); + +export default () => { + client.connect("localhost:10000", { plaintext: true }); + const response = client.invoke("main.RouteGuide/GetFeature", { + latitude: 410248224, + longitude: -747127767, + }); + check(response, { "status is OK": (r) => r && r.status === grpc.StatusOK }); + console.log(response.message.name); + // output: 3 Hasta Way, Newton, NJ 07860, USA + + client.close() +} +``` + +
+ diff --git a/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20 Client/40-Client-close.md b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20 Client/40-Client-close.md new file mode 100644 index 0000000000..270ccbce22 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20 Client/40-Client-close.md @@ -0,0 +1,23 @@ +--- +title: "Client.close()" +excerpt: 'Close the connection to the gRPC service. Tear down all underlying connections.' +--- + +Close the connection to the gRPC service. Tear down all underlying connections. + +### Examples + +
+ +```javascript +import grpc from "k6/net/grpc"; + +const client = new grpc.Client(); +client.load(['definitions'], 'hello.proto'); + +export default () => { + client.connect("localhost:8080"); + client.close(); +} +``` +
diff --git a/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20-Params.md b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20-Params.md new file mode 100644 index 0000000000..195b36be47 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/20-Params.md @@ -0,0 +1,39 @@ +--- +title: "Params" +head_title: 'gRPC.params' +excerpt: 'Params is an object used by the gRPC methods that generate RPC requests.' +--- + +*Params* is an object used by the gRPC methods that generate RPC requests. *Params* contains request-specific options like headers that should be inserted into the request. + +| Name | Type | Description | +|------|------|-------------| +| `Params.headers` | object | Object with key-value pairs representing custom headers the user would like to add to the request. | +| `Params.tags` | object | Key-value pairs where the keys are names of tags and the values are tag values. Response time metrics generated as a result of the request will have these tags added to them, allowing the user to filter out those results specifically, when looking at results data. | +| `Params.timeout` | number | Request timeout to use. Default timeout is 60 seconds (`"60s"`). | + + +### Example of custom metadata headers and tags + +
+ +```javascript +import grpc from "k6/net/grpc"; + +const client = new grpc.Client(); +client.load([], "route_guide.proto"); + +export default function () { + const req = { + latitude: 410248224, + longitude: -747127767, + }; + const params = { + headers: { "x-my-header": "k6test" }, + tags: { k6test: "yes" }, + }; + const response = client.invoke("main.RouteGuide/GetFeature", req, params); +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/30-Response.md b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/30-Response.md new file mode 100644 index 0000000000..55702f21bc --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/30-Response.md @@ -0,0 +1,43 @@ +--- +title: "Response" +head_title: 'gRPC.Response' +excerpt: 'The response object of a gRPC request.' +--- + +| Name | Type | Description | +|------|------|-------------| +| `Response.status` | number | The response gRPC status code. Use the gRPC [status constants](/javascript-api/v0-31/k6-net-grpc/constants) to check equality. | +| `Response.message` | object | The successful protobuf message, serialized to JSON. Will be `null` if `status !== grpc.StatusOK`. | +| `Response.headers` | object | Key-value pairs representing all the metadata headers returned by the gRPC server. | +| `Response.trailers` | object | Key-value pairs representing all the metadata trailers returned by the gRPC server. | +| `Response.error` | object | If `status !== grpc.StatusOK` then the error protobuf message, serialized to JSON; otherwise `null`. | + +### Example + + + +```javascript +import grpc from 'k6/net/grpc'; +import { check } from 'k6'; + +const client = new grpc.Client(); +client.load(['definitions'], 'hello.proto'); + +export default () => { + client.connect('grpcb.in:9001', { + // plaintext: false + }); + + const data = { greeting: 'Bert' }; + const response = client.invoke('hello.HelloService/SayHello', data); + + check(response, { + 'status is OK': (r) => r && r.status === grpc.StatusOK, + }); + + client.close(); + sleep(1); +}; +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/40-Constants.md b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/40-Constants.md new file mode 100644 index 0000000000..e88986d6d9 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/09 k6-net-grpc/40-Constants.md @@ -0,0 +1,56 @@ +--- +title: 'Constants' +excerpt: 'Define constants to distinguish between gRPC Response' +--- + +Define constants to distinguish between [gRPC Response](/javascript-api/v0-31/k6-net-grpc/response) statuses. + +| Constant | Description | +|----------|-------------| +| `StatusOK` | OK is returned on success. | +| `StatusCanceled` | Canceled indicates the operation was canceled (typically by the caller). | +| `StatusUnknown` | Unknown error. | +| `StatusInvalidArgument` | InvalidArgument indicates the client specified an invalid argument. | +| `StatusDeadlineExceeded` | DeadlineExceeded means operation expired before completion. | +| `StatusNotFound` | NotFound means some requested entity (e.g., file or directory) was not found. | +| `StatusAlreadyExists` | AlreadyExists means an attempt to create an entity failed because one already exists. | +| `StatusPermissionDenied` | PermissionDenied indicates the caller does not have permission to execute the specified operation. | +| `StatusResourceExhausted` | ResourceExhausted indicates some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space. | +| `StatusFailedPrecondition` | FailedPrecondition indicates operation was rejected because the system is not in a state required for the operation's execution. | +| `StatusAborted` | Aborted indicates the operation was aborted, typically due to a concurrency issue like sequencer check failures, transaction aborts, etc. | +| `StatusOutOfRange` | OutOfRange means operation was attempted past the valid range. E.g., seeking or reading past end of file. | +| `StatusUnimplemented` | Unimplemented indicates operation is not implemented or not supported/enabled in this service. | +| `StatusInternal` | Internal errors. Means some invariants expected by the underlying system have been broken. | +| `StatusUnavailable` | Unavailable indicates the service is currently unavailable. This is a most likely a transient condition and may be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations. | +| `StatusDataLoss` | DataLoss indicates unrecoverable data loss or corruption. | +| `StatusUnauthenticated` | Unauthenticated indicates the request does not have valid authentication credentials for the operation. | + +### Example + + + +```javascript +import grpc from 'k6/net/grpc'; +import { check } from 'k6'; + +const client = new grpc.Client(); +client.load(['definitions'], 'hello.proto'); + +export default () => { + client.connect('grpcb.in:9001', { + // plaintext: false + }); + + const data = { greeting: 'Bert' }; + const response = client.invoke('hello.HelloService/SayHello', data); + + check(response, { + 'status is OK': (r) => r && r.status === grpc.StatusOK, + }); + + client.close(); + sleep(1); +}; +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/10 k6-ws.md b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws.md new file mode 100644 index 0000000000..ea42dd43a1 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws.md @@ -0,0 +1,24 @@ +--- +title: "k6/ws" +excerpt: "k6 WebSocket API" +--- + +The ws module provides a [WebSocket](https://en.wikipedia.org/wiki/WebSocket) client implementing the [WebSocket protocol](http://www.rfc-editor.org/rfc/rfc6455.txt). + +| Function | Description | +| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [connect( url, params, callback )](/javascript-api/v0-31/k6-ws/connect-url-params-callback) | Create a WebSocket connection, and provides a [Socket](/javascript-api/v0-31/k6-ws/socket) client to interact with the service. The method blocks the test finalization until the connection is closed. | + +| Class/Method | Description | +| ----- | ----------- | +| [Socket](/javascript-api/v0-31/k6-ws/socket) | WebSocket client used to interact with a WS connection. | +| [Socket.close()](/javascript-api/v0-31/k6-ws/socket/socket-close) | Close the WebSocket connection. | +| [Socket.on(event, callback)](/javascript-api/v0-31/k6-ws/socket/socket-on-event-callback) | Set up an event listener on the connection for any of the following events:
- open
- message
- ping
- pong
- close
- error. | +| [Socket.ping()](/javascript-api/v0-31/k6-ws/socket/socket-ping) | Send a ping. | +| [Socket.send(data)](/javascript-api/v0-31/k6-ws/socket/socket-send-data) | Send data. | +| [Socket.setInterval(callback, interval)](/javascript-api/v0-31/k6-ws/socket/socket-setinterval-callback-interval) | Call a function repeatedly at certain intervals, while the connection is open. | +| [Socket.setTimeout(callback, period)](/javascript-api/v0-31/k6-ws/socket/socket-settimeout-callback-delay) | Call a function with a delay, if the connection is open. | + + + + diff --git a/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/10-connect- url- params- callback -.md b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/10-connect- url- params- callback -.md new file mode 100644 index 0000000000..196565b1eb --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/10-connect- url- params- callback -.md @@ -0,0 +1,47 @@ +--- +title: 'connect( url, params, callback )' +description: 'Create a WebSocket connection, and provides a Socket client to interact with the service.' +excerpt: 'Create a WebSocket connection, and provides a Socket client to interact with the service.' +--- + +Initiate a WebSocket connection to a remote host. + +Calling connect will block the VU finalization until the WebSocket connection is closed. Instead of continuously looping the main function (`export default function() { ... }`) over an over, each VU will be halted listening to async events and executing their event handlers until the connection is closed. + +The following events can close the connection: + +- remote host close event. +- [Socket.close()](/javascript-api/v0-31/k6-ws/socket/socket-close). +- k6 VU interruption based on test configuration or CLI commands. + +| Parameter | Type | Description | +| --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| url | string | Request URL (e.g. "ws://echo.websocket.org"). | +| params | object | [Params](/javascript-api/v0-31/k6-http/params) object containing additional request parameters. | +| callback | function | The callback function that will be called when the WebSocket connection is initiated. A [Socket](/javascript-api/v0-31/k6-ws/socket) object will be passed to the function, and this object can be used to set up callbacks etc when things happen on the WebSocket connection | + +### Returns + +| Type | Description | +| -------------------------------------------- | --------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | HTTP Response object. | + +### Example + + + +```javascript +import ws from 'k6/ws'; + +export default function () { + var url = 'ws://echo.websocket.org'; + var resp = ws.connect(url, null, function (socket) { + socket.on('open', function () { + console.log('WebSocket connection established!'); + socket.close(); + }); + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket.md b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket.md new file mode 100644 index 0000000000..66c1b57f34 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket.md @@ -0,0 +1,93 @@ +--- +title: 'Socket' +excerpt: 'Socket is a WebSocket client to interact with a WebSocket connection.' +--- + +`Socket` is a WebSocket client to interact with a WebSocket connection. You can use it to listen various events happening on the WebSocket connection and send messages to the server. Additionally, you can use socket.setTimeout() and socket.setInterval() to execute code in the background, or repeatedly, while the WebSocket connection is open. + +| Method | Description | +| ----------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Socket.close()](/javascript-api/v0-31/k6-ws/socket/socket-close) | Close the WebSocket connection. | +| [Socket.on(event, callback)](/javascript-api/v0-31/k6-ws/socket/socket-on-event-callback) | Set up an event listener on the connection for any of the following events:
- open
- message
- ping
- pong
- close
- error. | +| [Socket.ping()](/javascript-api/v0-31/k6-ws/socket/socket-ping) | Send a ping. | +| [Socket.send(data)](/javascript-api/v0-31/k6-ws/socket/socket-send-data) | Send data. | +| [Socket.setInterval(callback, interval)](/javascript-api/v0-31/k6-ws/socket/socket-setinterval-callback-interval) | Call a function repeatedly at certain intervals, while the connection is open. | +| [Socket.setTimeout(callback, period)](/javascript-api/v0-31/k6-ws/socket/socket-settimeout-callback-delay) | Call a function with a delay, if the connection is open. | + +### WebSocket built-in metrics + +`k6` will automatically collect some metrics when interacting with a WebSocket service through the `k6/ws` API. + +| Metric name | Type | Description | +| ------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------- | +| ws_connecting | Trend | Total duration for the WebSocket connection request. | +| ws_session_duration | Trend | Duration of the WebSocket session. Time between the start of the connection and the end of the VU execution. | +| ws_sessions | Counter | Total number of started WebSocket sessions. | +| ws_ping | Trend | Duration between a ping request and its pong reception | +| ws_msgs_sent | Counter | Total number of messages sent through [Socket.send(data)](/javascript-api/v0-31/k6-ws/socket/socket-send-data) | +| ws_msgs_received | Counter | Total number of received messages [Socket.on('message', callback)](/javascript-api/v0-31/k6-ws/socket/socket-on-event-callback). | + +Check out the [Results output article](/getting-started/results-output) for more information about how to process the metric information. + +### Example + + + +```javascript +import ws from 'k6/ws'; +import { check } from 'k6'; + +export default function () { + var url = 'ws://echo.websocket.org'; + var params = { tags: { my_tag: 'hello' } }; + + var response = ws.connect(url, params, function (socket) { + socket.on('open', function open() { + console.log('connected'); + socket.send(Date.now()); + + socket.setInterval(function timeout() { + socket.ping(); + console.log('Pinging every 1sec (setInterval test)'); + }, 1000); + }); + + socket.on('ping', function () { + console.log('PING!'); + }); + + socket.on('pong', function () { + console.log('PONG!'); + }); + + socket.on('pong', function () { + // Multiple event handlers on the same event + console.log('OTHER PONG!'); + }); + + socket.on('message', function (message) { + console.log(`Received message: ${message}`); + }); + + socket.on('close', function () { + console.log('disconnected'); + }); + + socket.on('error', function (e) { + if (e.error() != 'websocket: close sent') { + console.log('An unexpected error occured: ', e.error()); + } + }); + + socket.setTimeout(function () { + console.log('2 seconds passed, closing the socket'); + socket.close(); + }, 2000); + }); + + check(response, { 'status is 101': (r) => r && r.status === 101 }); +} +//VU execution won't be completely finished until the connection is closed. +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-close--.md b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-close--.md new file mode 100644 index 0000000000..38ea95db19 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-close--.md @@ -0,0 +1,25 @@ +--- +title: 'Socket.close()' +excerpt: 'Close the WebSocket connection.' +--- + +Close the WebSocket connection. + +### Example + + + +```javascript +import ws from 'k6/ws'; + +export default function () { + var url = 'ws://echo.websocket.org'; + var response = ws.connect(url, null, function (socket) { + socket.on('open', function () { + socket.close(); + }); + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-on-event- callback-.md b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-on-event- callback-.md new file mode 100644 index 0000000000..795351668f --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-on-event- callback-.md @@ -0,0 +1,82 @@ +--- +title: 'Socket.on(event, callback)' +excerpt: 'Set up callback functions for various events on the WebSocket connection.' +--- + +Set up callback functions for various events on the WebSocket connection. Multiple handlers can be defined for the same event. + +| Parameter | Type | Description | +| --------- | -------- | -------------------------------------------- | +| event | string | The event name to define a callback for. | +| callback | function | The function to call when the event happens. | + +| Event name | Description | +| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| open | Emitted when the connection is established | +| message | Emitted when a message is received from the server. | +| ping | Emitted when a ping is received from the server. The client will automatically send back a `pong`. | +| pong | Emitted when a pong is received from the server. | +| close | Emitted when the connection is closed by the client [Socket.close()](/javascript-api/v0-31/k6-ws/socket/socket-close) or when the server sends the `close` event with code status 1000 (normal closure). | +| error | Emitted when an error occurs. Non-normal closure errors will be forwarded. | + +### Example + + + +```javascript +import ws from 'k6/ws'; +import { check } from 'k6'; + +export default function () { + var url = 'ws://echo.websocket.org'; + var params = { tags: { my_tag: 'hello' } }; + + var response = ws.connect(url, params, function (socket) { + socket.on('open', function open() { + console.log('connected'); + socket.send(Date.now()); + + socket.setInterval(function timeout() { + socket.ping(); + console.log('Pinging every 1sec (setInterval test)'); + }, 1000); + }); + + socket.on('ping', function () { + console.log('PING!'); + }); + + socket.on('pong', function () { + console.log('PONG!'); + }); + + socket.on('pong', function () { + // Multiple event handlers on the same event + console.log('OTHER PONG!'); + }); + + socket.on('message', function (message) { + console.log(`Received message: ${message}`); + }); + + socket.on('close', function () { + console.log('disconnected'); + }); + + socket.on('error', function (e) { + if (e.error() != 'websocket: close sent') { + console.log('An unexpected error occured: ', e.error()); + } + }); + + socket.setTimeout(function () { + console.log('2 seconds passed, closing the socket'); + socket.close(); + }, 2000); + }); + + check(response, { 'status is 101': (r) => r && r.status === 101 }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-ping--.md b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-ping--.md new file mode 100644 index 0000000000..9e010a4921 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-ping--.md @@ -0,0 +1,30 @@ +--- +title: 'Socket.ping()' +excerpt: 'Send a ping. Ping messages can be used to verify that the remote endpoint is responsive.' +--- + +Send a ping. Ping messages can be used to verify that the remote endpoint is responsive. + +### Example + + + +```javascript +import ws from 'k6/ws'; + +export default function () { + var url = 'ws://echo.websocket.org'; + var response = ws.connect(url, null, function (socket) { + socket.on('open', function () { + socket.on('pong', function () { + // As required by the spec, when the ping is received, the recipient must send back a pong. + console.log('connection is alive'); + }); + + socket.ping(); + }); + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-send-data-.md b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-send-data-.md new file mode 100644 index 0000000000..252981a97a --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-send-data-.md @@ -0,0 +1,31 @@ +--- +title: 'Socket.send(data)' +excerpt: 'Send a data string through the connection. Binary data is not currently supported.' +--- + +Send a data string through the connection. Binary data is not currently supported. +You can use `JSON.stringify` to convert a JSON or JavaScript values to a JSON string. + +| Parameter | Type | Description | +| --------- | ------ | ----------------- | +| data | string | The data to send. | + +### Example + + + +```javascript +import ws from 'k6/ws'; + +export default function () { + var url = 'ws://echo.websocket.org'; + var response = ws.connect(url, null, function (socket) { + socket.on('open', function () { + socket.send('my-message'); + socket.send(JSON.stringify({ data: 'hola' })); + }); + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-setInterval-callback- interval-.md b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-setInterval-callback- interval-.md new file mode 100644 index 0000000000..07a624ae78 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-setInterval-callback- interval-.md @@ -0,0 +1,44 @@ +--- +title: 'Socket.setInterval(callback, interval)' +excerpt: 'Call a function repeatedly, while the WebSocket connection is open.' +--- + +Call a function repeatedly, while the WebSocket connection is open. + +| Parameter | Type | Description | +| --------- | -------- | ----------------------------------------------------------- | +| callback | function | The function to call every `interval` milliseconds. | +| interval | number | The number of milliseconds between two calls to `callback`. | + +### Example + + + +```javascript +import ws from 'k6/ws'; +import { check } from 'k6'; + +export default function () { + var url = 'ws://echo.websocket.org'; + var params = { tags: { my_tag: 'hello' } }; + + var res = ws.connect(url, params, function (socket) { + socket.on('open', function open() { + console.log('connected'); + + socket.setInterval(function timeout() { + socket.ping(); + console.log('Pinging every 1sec (setInterval test)'); + }, 1000); + }); + + socket.on('pong', function () { + console.log('PONG!'); + }); + }); + + check(res, { 'status is 101': (r) => r && r.status === 101 }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-setTimeout-callback- delay-.md b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-setTimeout-callback- delay-.md new file mode 100644 index 0000000000..74c0288dd2 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/10 k6-ws/80 Socket/Socket-setTimeout-callback- delay-.md @@ -0,0 +1,43 @@ +--- +title: 'Socket.setTimeout(callback, delay)' +excerpt: 'Call a function at a later time, if the WebSocket connection is still open then.' +--- + +Call a function at a later time, if the WebSocket connection is still open then. + +| Parameter | Type | Description | +| --------- | -------- | ---------------------------------------------- | +| callback | function | The function to call when `delay` has expired. | +| delay | number | The delay time, in milliseconds. | + +### Example + + + +```javascript +import ws from 'k6/ws'; +import { sleep } from 'k6'; + +export default function () { + console.log('T0: Script started'); + var url = 'ws://echo.websocket.org'; + var response = ws.connect(url, null, function (socket) { + console.log('T0: Entered WebSockets run loop'); + socket.setTimeout(function () { + console.log('T0+1: This is printed'); + }, 1000); + socket.setTimeout(function () { + console.log('T0+2: Closing socket'); + socket.close(); + }, 2000); + socket.setTimeout(function () { + console.log('T0+3: This is not printed, because socket is closed'); + }, 3000); + }); + console.log('T0+2: Exited WebSockets run loop'); + sleep(2); + console.log('T0+4: Script finished'); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib.md new file mode 100644 index 0000000000..8850264ec9 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib.md @@ -0,0 +1,63 @@ +--- +title: "jslib" +excerpt: "External JavaScript libraries for k6" +--- + +The [jslib.k6.io](https://jslib.k6.io/) is a collection of external JavaScript libraries that can be [directly imported](https://k6.io/docs/using-k6/modules#remote-http-s-modules) in k6 scripts. + + +| Library | Description | +| -------- | ----------- | +| [utils](/javascript-api/v0-31/jslib/utils) | Small utility functions useful in every day load testing | +| [expect](/javascript-api/v0-31/jslib/expect) | Micro-framework for writing tests in a style of Jest or ava. | +| [httpx](/javascript-api/v0-31/jslib/httpx) | Wrapper around the http that simplifies session handling | +| - | Documentation for other libraries will be added shortly. | + + + +### Example + + + +```javascript +import { check, sleep } from "k6"; +import jsonpath from "https://jslib.k6.io/jsonpath/1.0.2/index.js" +import { randomIntBetween, + randomItem, + uuidv4 } from "https://jslib.k6.io/k6-utils/1.1.0/index.js"; + +const testData = { + user: { + name: "Batman" + } +}; + +export default function() { + check(testData, { + "JSON path works": () => jsonpath.value(testData, 'user.name') === "Batman" + }); + + console.log(uuidv4()); + console.log(randomItem([1,2,3,4])); + + sleep(randomIntBetween(1,5)); // sleep between 1 and 5 seconds +} +``` + + + +The complete list of supported libraries can be viewed on [jslib.k6.io](https://jslib.k6.io). + +## Versioning + +``` +https://jslib.k6.io/library-name/version/index.js +``` + +Libraries hosted on jslib have versions. For example "httpx.js" library currently has v0.0.1, v0.0.2 and v0.0.3. + +We recommend that you use the last version available at the time of writing your k6 scripts. Older versions will continue to be hosted on jslib, so you don't have to worry about your scripts breaking. + +This documentation is for the last version of these libraries. If the examples documented here don't work, please check that you are using the latest version. + +If you don't want to depend on jslib or want to make modifications to the code, you can download the libraries and use them locally. diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/01 utils.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/01 utils.md new file mode 100644 index 0000000000..b01015c53e --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/01 utils.md @@ -0,0 +1,55 @@ +--- +title: "utils" +excerpt: "A collection of small utility functions useful during load testing with k6. " +--- + +The `utils` module contains number of small utility functions useful in every day load testing. + +> ⭐️ Source code available on [GitHub](https://github.com/k6io/k6-jslib-utils). +> Please request features and report bugs through [GitHub issues](https://github.com/k6io/k6-jslib-utils/issues). + + + + + +| Function | Description | +| -------- | ----------- | +| [randomIntBetween(min, max)](/javascript-api/v0-31/jslib/utils/randomintbetween-min-max) | Random integer in a given range | +| [randomItem(array)](/javascript-api/v0-31/jslib/utils/randomitem-array) | Random item from a given array | +| [randomString(length)](/javascript-api/v0-31/jslib/utils/randomstring-length) | Random string of a given length | +| [uuidv4()](/javascript-api/v0-31/jslib/utils/uuidv4) | Random UUID v4 in a string representation | +| [findBetween(content, left, right)](/javascript-api/v0-31/jslib/utils/findbetween-content-left-right) | Extract a string between two surrounding strings | + + +## Simple example + + + +```javascript +import { sleep } from 'k6'; +import http from 'k6/http'; + +import { randomIntBetween, + randomString, + randomItem, + uuidv4, + findBetween } from "https://jslib.k6.io/k6-utils/1.1.0/index.js"; + +export default function() { + + let res = http.post(`https://test-api.k6.io/user/register/`, { + first_name: randomItem(['Joe', 'Jane']), // random name + last_name: 'Smith', + username: `user_${randomString(10)}@example.com`, // random email address, + password: uuidv4() // random password in form of uuid + }); + + // find a string between two strings to grab the username: + let username = findBetween(res.body, '"username":"', '"'); + console.log('username from response: ' + username); + + sleep(randomIntBetween(1, 5)); // sleep between 1 and 5 seconds. +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/02 httpx.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/02 httpx.md new file mode 100644 index 0000000000..b83c3f58a3 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/02 httpx.md @@ -0,0 +1,118 @@ +--- +title: "httpx" +excerpt: "httpx is a wrapper library around the native k6 http module" +--- + +The `httpx` module is an external JavaScript library that wraps around the native [k6/http](/javascript-api/v0-31/k6-http) module. +It's a http client with features that are not yet available in the native module. + - ability to set http options globally (such as timeout) + - ability to set default tags and headers that will be used for all requests + - more user-friendly arguments to request functions (get, post, put take the same arguments) + +httpx module integrates well with expect library. + +> ⭐️ Source code available on [GitHub](https://github.com/k6io/k6-jslib-httpx). . +> Please request features and report bugs through [GitHub issues](https://github.com/k6io/k6-jslib-httpx/issues). + + +
+ +#### This library is in active development + +This library is stable enough to be useful, but pay attention to the new versions released on [jslib.k6.io](https://jslib.k6.io). + +This documentation is for the last version only. If you discover that some of the code below does not work, it most likely means that you are using an older version. + +
+ + +### Methods + +| Function | Description | +| -------- | ----------- | +| [request(method, url, [body], [params])](/javascript-api/v0-31/jslib/httpx/request-method-url-body-params) | Generic method for making arbitrary HTTP requests. | +| [get(url, [body], [params])](/javascript-api/v0-31/jslib/httpx/get-url-body-params) | Makes GET request | +| [post(url, [body], [params])](/javascript-api/v0-31/jslib/httpx/post-url-body-params) | Makes POST request | +| [put(url, [body], [params])](/javascript-api/v0-31/jslib/httpx/put-url-body-params) | Makes PUT request | +| [patch(url, [body], [params])](/javascript-api/v0-31/jslib/httpx/patch-url-body-params) | Makes PATCH request | +| [delete(url, [body], [params])](/javascript-api/v0-31/jslib/httpx/delete-url-body-params) | Makes DELETE request | +| [batch(requests)](/javascript-api/v0-31/jslib/httpx/batch-requests) | Batch multiple HTTP requests together, to issue them in parallel. | +| [setBaseUrl(url)](/javascript-api/v0-31/jslib/httpx/setbaseurl-url) | Sets the base URL for the session | +| [addHeader(key, value)](/javascript-api/v0-31/jslib/httpx/addheader-key-value) | Adds a header to the session | +| [addHeaders(object)](/javascript-api/v0-31/jslib/httpx/addheaders-object) | Adds multiple headers to the session | +| [clearHeader(name)](/javascript-api/v0-31/jslib/httpx/clearheader-name) | Removes header from the session | +| [addTag(key, value)](/javascript-api/v0-31/jslib/httpx/addtag-key-value) | Adds a tag to the session | +| [addTags(object)](/javascript-api/v0-31/jslib/httpx/addtags-object) | Adds multiple tags to the session | +| [clearTag(name)](/javascript-api/v0-31/jslib/httpx/cleartag-name) | Removes tag from the session | + + + + +### Example + + + +```javascript +import { fail } from 'k6'; +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.3/index.js'; +import { randomIntBetween } from "https://jslib.k6.io/k6-utils/1.1.0/index.js"; + +const USERNAME = `user${randomIntBetween(1, 100000)}@example.com`; // random email address +const PASSWORD = 'superCroc2021'; + +let session = new Httpx({ + baseURL: 'https://test-api.k6.io', + headers: { + 'User-Agent': "My custom user agent", + "Content-Type": 'application/x-www-form-urlencoded' + }, + timeout: 20000 // 20s timeout. +}); + +export default function testSuite() { + + let registrationResp = session.post(`/user/register/`, { + first_name: 'Crocodile', + last_name: 'Owner', + username: USERNAME, + password: PASSWORD, + }); + + if (registrationResp.status !== 201){ + fail("registration failed") + } + + let loginResp = session.post(`/auth/token/login/`, { + username: USERNAME, + password: PASSWORD + }); + + if(loginResp.status !== 200){ + fail("Authentication failed"); + } + + let authToken = loginResp.json('access'); + + // set the authorization header on the session for the subsequent requests. + session.addHeader('Authorization', `Bearer ${authToken}`); + + let payload = { + name: `Croc Name`, + sex: "M", + date_of_birth: '2019-01-01', + }; + + // this request uses the Authorization header set above. + let respCreateCrocodile = session.post(`/my/crocodiles/`, payload); + + if(respCreateCrocodile.status !== 201){ + fail("Crocodile creation failed"); + } + else{ + console.log("New crocodile created"); + } +} + +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/03 expect.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/03 expect.md new file mode 100644 index 0000000000..876a580aa2 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/03 expect.md @@ -0,0 +1,129 @@ +--- +title: "expect" +excerpt: "Functional testing and specifying robust expectations with k6" +--- + +The `expect` module is a JavaScript library that simplifies specifying expecatation about the responses from the target system. The design of the `expect` library was inspired by ava, Jest and Jasmine. If you already know one of these frameworks, using this library should be very simple. + +This library is especially useful for: + - Functional testing, where many asserts are needed + - Stress testing, where the System Under Test is failing and the test code needs to stay robust. + - Load testing, where the failures of the System Under Test need to be robustly collected for analysis + +> ⭐️ Source code available on [GitHub](https://github.com/k6io/k6-jslib-expect). +> Please request features and report bugs through [GitHub issues](https://github.com/k6io/k6-jslib-expect/issues). + +
+ +#### This library is rapidly evolving. + +This library is stable enough to be useful, but pay attention to the new versions released on [jslib.k6.io](https://jslib.k6.io). + +This documentation is for the last version only. If you discover that some of the code below does not work, it most likely means that you are using an older version. + +
+ +## Installation +There's nothing to install. This library is hosted on [jslib](https://jslib.k6.io/) and can be imported in the k6 script directly. + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +``` + + + +Alternatively, you can use a copy of this file stored locally. + +## Simple example + +Let's get started by writing a test for a hypothetical HTTP API that should return a JSON array of objects. + +First, create a `mytest.js` k6 script file. + + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + describe('Basic API test', (t) => { + let response = http.get("https://test-api.k6.io/public/crocodiles") + + t.expect(response.status).as("API status code").toEqual(200); + }) +} +``` + + + +If you are familiar with k6, this is similar to using the built-in `group` and `check` functionality but with different names. + +When you run this test with `k6 run mytest.js` the result should look similar to this: + +``` +█ Basic API test + ✓ response status is 200. +``` + +This basic example is not very exciting because the same result can be achieved with `group` and `check`, so let's move on to more interesting examples. + +### Chain of checks + +When writing integration tests and performance test, it's often necessary to execute conditional checks. For example, you may want to inspect the JSON body only when the http response is 200. If it's 500, the body is not relevant and should not be inspected. + +It's possible to chain checks using the `.and()` function, as shown below. + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + + describe('Fetch a list of public crocodiles', (t) => { + let response = http.get("https://test-api.k6.io/public/crocodiles") + + t.expect(response.status).as("response status").toEqual(200) + .and(response).toHaveValidJson() + .and(response.json().length).as("number of crocs").toBeGreaterThan(5); + }) +} +``` + + + +When you run this test with `k6 run mytest.js`, the result should look similar to this: + +The above script should result in the following being printed after execution: + +``` +█ Fetch a list of public crocodiles + ✓ response status is 200. + ✓ https://test-api.k6.io/public/crocodiles has valid json response + ✓ number of crocs is greater than 5 +``` + +More advanced examples can be found in the [examples section](/examples/functional-testing) + + +| Function | Description | +| -------- | ----------- | +| [describe(name, function)](/javascript-api/v0-31/jslib/expect/describe-name-function) | Entry point for creating tests. | +| [expect(value)](/javascript-api/v0-31/jslib/expect/expect-value) | expect(value) sets the value to be used in comparison by the next function in the chain | +| [and(value)](/javascript-api/v0-31/jslib/expect/and-value) | and(value) is similar to expect(value), but can be used in a chain. | +| [as(alias)](/javascript-api/v0-31/jslib/expect/as-string) | as(alias) sets a textual representation of the value passed to `expect` or `and`. | +| [toEqual(value)](/javascript-api/v0-31/jslib/expect/toequal-expectedvalue) | The `.toEqual(expectedValue)` is similar to `===` | +| [toBeGreaterThan(expectedValue)](/javascript-api/v0-31/jslib/expect/tobegreaterthan-expectedvalue) | Use to verify that `received` > `expected` | +| [toBeGreaterThanOrEqual(expectedValue)](/javascript-api/v0-31/jslib/expect/tobegreaterthanorequal-expectedvalue) | Use to verify that `received` >= `expected` | +| [toBeLessThan(expectedValue)](/javascript-api/v0-31/jslib/expect/tobelessthan-expectedvalue) | Use to verify that `received` < `expected` | +| [toBeLessThanOrEqual(expectedValue)](/javascript-api/v0-31/jslib/expect/tobelessthanorequal-expectedvalue) | Use to verify that `received` <= `expected` | +| [toBeBetween(from, to)](/javascript-api/v0-31/jslib/expect/tobebetween-from-to) | Use to verify that expected value is within range. | +| [toBeTruthy()](/javascript-api/v0-31/jslib/expect/tobetruthy) | Use `.toBeTruthy` when you don't care what a value is and you want to ensure a value is true in a boolean context. | +| [toHaveValidJson()](/javascript-api/v0-31/jslib/expect/tohavevalidjson) | Use to verify that the http response has a valid JSON body. | + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/10 error handling.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/10 error handling.md new file mode 100644 index 0000000000..d4880bbd8a --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/10 error handling.md @@ -0,0 +1,99 @@ +--- +title: 'Error handling in expect.js' +description: 'How to handle errors in expect.js.' +excerpt: 'How to handle errors in expect.js.' +--- + +When executing a performance or integration test, you should expect that your system under test may crash. If this happens, your test should print useful information rather than stack traces caused by unexpected HTTP responses. + +`expect` library is designed to make it easy to write test scripts that are resilient to failing SUT (System Under Test). + +It's not uncommon for performance testers to write fragile code that assumes the http response will contain expected data. + +Fragile code is most clearly demonstrated with an example. + + + +```javascript +import { check, group } from 'k6'; +import http from 'k6/http'; + +export default function() { + group("Fetch a list of public crocodiles", () => { + let res = http.get("https://test-api.k6.io/public/crocodiles"); + + check(res, { + 'is status 200': (r) => r.status === 200, + 'got more than 5 crocs': (r) => r.json().length > 5, + }); + }) + // more code here +} +``` + + + + +This code will work fine as long as SUT (System Under Test) returns correct responses. When the SUT starts to fail, there's a good chance the `r.json().length` will throw an exception similar to + +```bash +ERRO[0001] GoError: cannot parse json due to an error at line 1, character 2 , error: invalid character '<' looking for beginning of value +running at reflect.methodValueCall (native) +default at gotMoreThan5Crocs (file:///home/user/happy-path-check.js:7:68(5)) + at github.com/k6io/k6/js/common.Bind.func1 (native) + at file:///home/user/happy-path-check.js:5:22(17) executor=per-vu-iterations scenario=default source=stacktrace +``` + +In this example, the system was overloaded, and the load balancer returned a 503 response that did not have a valid JSON body. k6 has thrown a JavaScript exception and restarted execution from the beginning. +This test code is fragile to failing SUT because the first `check` does not prevent the second check from executing. +It's possible to rewrite this code to be less fragile, but that will make it longer and less readable. + +Error handling of this type happens automatically when using the `expect.js` library. +When the first `expect` fails, the remaining checks in the chain are not executed, and the test is marked as failed — the execution proceeds to the next `describe()` instead of restarting from the top. + + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function() { + describe('Fetch a list of public crocodiles', (t) => { + let response = http.get("https://test-api.k6.io/public/crocodiles") + + t.expect(response.status).as("response status").toEqual(200) + .and(response).toHaveValidJson() + .and(response.json().length).as("number of crocs").toBeGreaterThan(5); + }) + // more code here +} +``` + + + +# Handling exceptions + +Sometimes it's hard to predict the way SUT can fail. For those cases, the `expect` library caught any exceptions thrown inside of `describe()` body, and records it as a failed condition. + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + + describe('Executing test against a Shaky SUT', (t) => { + throw("Something entirely unexpected happened"); + }); +} +``` + + + +Execution of this script should print the following output. + + +![output](./images/exception-handling.png) + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/20 describe(name, function) copy.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/20 describe(name, function) copy.md new file mode 100644 index 0000000000..1e1023e2ed --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/20 describe(name, function) copy.md @@ -0,0 +1,66 @@ +--- +title: 'describe( name, function )' +description: 'Entry point for creating test cases.' +excerpt: 'Entry point for creating test cases.' +--- + + +To declare a new test case you call the `describe(name, function)` function. Provide the required name and implementation function. +Names should be unique within the script, otherwise, the test cases will to be grouped. + +Note: The first argument of the implementation function should be named `t`. + +Behind the scenes, the `describe()` function creates a k6 [group](/javascript-api/v0-31/k6/group-name-fn). + + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| name | string | Test case name | +| function | function | The function to be executed | + + +### Returns + +| Type | Description | +| ------- | ------------------------------- | +| bool | Returns true when all `expect` and `and` conditions within the `describe()` body were successful, and no unhandled exceptions were raised, otherwise false. | + +### Example + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + + let success1 = describe('Basic test', (t) => { + t.expect(1).toEqual(1) + }) + + console.log(success1); // true + + let success2 = describe('Another test', (t) => { + throw("Something entirely unexpected happened"); + }); + + console.log(success2); // false + + let success3 = describe('Yet another test', (t) => { + t.expect(true).toEqual(false); + }); + + console.log(success3); // false + +} +``` + + + +Execution of this script should print the following output. + + +![output](./images/test-output.png) + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/21 expect(value).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/21 expect(value).md new file mode 100644 index 0000000000..3a3abaccb3 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/21 expect(value).md @@ -0,0 +1,37 @@ +--- +title: 'expect( value )' +description: 'expect(value) sets the value to be used in comparison by the next function in the chain.' +excerpt: 'expect(value) sets the value to be used in comparison by the next function in the chain.' +--- + +`expect(value)` sets the value to be used in comparison by the next function in the chain. + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| value | any | The value to be compared | + + +### Returns + +| Type | Description | +| ------ | ------------------------------- | +| Funk | Funk object | + +### Example + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + describe('Basic API test', (t) => { + let response = http.get("https://test-api.k6.io/public/crocodiles") + t.expect(response.status).toEqual(200); + }) +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/22 and(value).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/22 and(value).md new file mode 100644 index 0000000000..32b1499a6f --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/22 and(value).md @@ -0,0 +1,42 @@ +--- +title: 'and(value)' +description: 'and(value) is similar to expect(value), but can be used in a chain.' +excerpt: 'and(value) is similar to expect(value), but can be used in a chain.' +--- + +`and(value)` works the same as `expect(value)`, but can be used to chain multiple tests together. + + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| value | any | The value to be compared | + + +### Returns + +| Type | Description | +| ------ | ------------------------------- | +| Funk | Funk object | + +### Example + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + + describe('Basic API test', (t) => { + let response = http.get("https://test-api.k6.io/public/crocodiles") + + t.expect(response.status).as("response status").toEqual(200) + .and(response).toHaveValidJson() + .and(response.json().length).as("number of crocs").toBeGreaterThan(5); + }) +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/23 as(alias).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/23 as(alias).md new file mode 100644 index 0000000000..2b143dbcff --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/23 as(alias).md @@ -0,0 +1,39 @@ +--- +title: 'as( string )' +description: 'as(alias) sets a textual representation of the value passed to expect or and.' +excerpt: 'as(alias) sets a textual representation of the value passed to expect or and.' +--- + + +| Parameter | Type | Description | +| -------------- | ------ | ---- | +| name | string | Sets the textual representation of the value passed to `expect()` or `and()` | + + +### Returns + +| Type | Description | +| ------ | ------------------------------- | +| Funk | Funk object | + +### Example + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + + describe('Basic API test', (t) => { + let response = http.get("https://test-api.k6.io/public/crocodiles") + + t.expect(response.status).as("response status").toEqual(200) + .and(response).toHaveValidJson() + .and(response.json().length).as("number of crocs").toBeGreaterThan(5); + }) +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/30 toEqual.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/30 toEqual.md new file mode 100644 index 0000000000..de655165ec --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/30 toEqual.md @@ -0,0 +1,44 @@ +--- +title: 'toEqual( expectedValue )' +description: 'Use to verify that received === expected' +excerpt: 'Use to verify that received === expected' +--- + +`toEqual(expectedValue)` is a comparison function that evaluates to true or false. It must be called in the chain after the `t.expect(value)` or `.and(value)`. + +`toEqual` is equivalent to `received === expected` + +When `toEqual(expectedValue)` evaluates to false, the chain is broken, and the test is marked as failed. When the chain is broken, further checks inside of the `test` are omitted. + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| expectedValue | any | The expected value | + + +### Returns + +| Type | Description | +| ------ | ------------------------------- | +| Funk | Funk object | + +### Example + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + + describe('Basic API test', (t) => { + let response = http.get("https://test-api.k6.io/public/crocodiles") + + t.expect(response.status).toEqual(200); + t.expect(response.proto).toEqual("HTTP/2.0"); + }) +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/31 toBeGreaterThan.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/31 toBeGreaterThan.md new file mode 100644 index 0000000000..f0a66e43ba --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/31 toBeGreaterThan.md @@ -0,0 +1,43 @@ +--- +title: 'toBeGreaterThan( expectedValue )' +description: 'Use to verify that received > expected' +excerpt: 'Use to verify that received > expected' +--- + +`toBeGreaterThan(expectedValue)` is a comparison function that evaluates to true or false. It must be called in the chain after the `t.expect(value)` or `.and(value)`. + +`toBeGreaterThan` is equivalent to `received > expected` + +When `toBeGreaterThan(expectedValue)` evaluates to false, the chain is broken, and the test is marked as failed. When the chain is broken, further checks inside of the `test` are omitted. + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| expectedValue | any | The expected value | + + +### Returns + +| Type | Description | +| ------ | ------------------------------- | +| Funk | Funk object | + +### Example + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + + describe('Basic API test', (t) => { + t.expect(5).toBeGreaterThan(4); // true + t.expect(5).toBeGreaterThan(5); // false + t.expect(5).toBeGreaterThan(6); // false. Won't execute because previous statement was false + }) +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/32 toBeGreaterThanOrEqual.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/32 toBeGreaterThanOrEqual.md new file mode 100644 index 0000000000..72b11ea305 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/32 toBeGreaterThanOrEqual.md @@ -0,0 +1,43 @@ +--- +title: 'toBeGreaterThanOrEqual( expectedValue )' +description: 'Use to verify that received >= expected' +excerpt: 'Use to verify that received >= expected' +--- + +`toBeGreaterThanOrEqual(expectedValue)` is a comparison function that evaluates to true or false. It must be called in the chain after the `t.expect(value)` or `.and(value)`. + +`toBeGreaterThanOrEqual` is equivalent to `received >= expected` + +When `toBeGreaterThanOrEqual(expectedValue)` evaluates to false, the chain is broken, and the test is marked as failed. When the chain is broken, further checks inside of the `test` are omitted. + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| expectedValue | any | The expected value | + + +### Returns + +| Type | Description | +| ------ | ------------------------------- | +| Funk | Funk object | + +### Example + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + + describe('Basic API test', (t) => { + t.expect(5).toBeGreaterThanOrEqual(4); // true + t.expect(5).toBeGreaterThanOrEqual(5); // true + t.expect(5).toBeGreaterThanOrEqual(6); // false + }) +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/33 toBeLessThan.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/33 toBeLessThan.md new file mode 100644 index 0000000000..c2ab07b9d3 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/33 toBeLessThan.md @@ -0,0 +1,45 @@ +--- +title: 'toBeLessThan( expectedValue )' +description: 'Use to verify that `received < expected`' +excerpt: 'Use to verify that `received < expected`' +--- + +`toBeLessThan(expectedValue)` is a comparison function that evaluates to true or false. It must be called in the chain after the `t.expect(value)` or `.and(value)`. + +`toBeLessThan` is equivalent to `received < expected` + +When `toBeLessThan(expectedValue)` evaluates to false, the chain is broken, and the test is marked as failed. When the chain is broken, further checks inside of the `test` are omitted. + + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| expectedValue | any | The expected value | + + +### Returns + +| Type | Description | +| ------ | ------------------------------- | +| Funk | Funk object | + +### Example + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + + describe('Basic API test', (t) => { + t.expect(5).toBeLessThan(6); // true + t.expect(5).toBeLessThan(5); // false + t.expect(5).toBeLessThan(5); // false. Won't execute because previous statement was false + + }) +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/34 toBeLessThanOrEqual.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/34 toBeLessThanOrEqual.md new file mode 100644 index 0000000000..081789d5ad --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/34 toBeLessThanOrEqual.md @@ -0,0 +1,44 @@ +--- +title: 'toBeLessThanOrEqual( expectedValue )' +description: 'Use to verify that received <= expected' +excerpt: 'Use to verify that received <= expected' +--- + +`toBeLessThanOrEqual(expectedValue)` is a comparison function that evaluates to true or false. It must be called in the chain after the `t.expect(value)` or `.and(value)`. + +`toBeLessThanOrEqual` is equivalent to `received <= expected` + +When `toBeLessThanOrEqual(expectedValue)` evaluates to false, the chain is broken, and the test is marked as failed. When the chain is broken, further checks inside of the `test` are omitted. + + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| expectedValue | any | The expected value | + + +### Returns + +| Type | Description | +| ------ | ------------------------------- | +| Funk | Funk object | + +### Example + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + + describe('Basic API test', (t) => { + t.expect(5).toBeLessThanOrEqual(6); // true + t.expect(5).toBeLessThanOrEqual(5); // true + t.expect(5).toBeLessThanOrEqual(4); // false + }) +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/35 toBeBetween.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/35 toBeBetween.md new file mode 100644 index 0000000000..49b1042ef4 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/35 toBeBetween.md @@ -0,0 +1,53 @@ +--- +title: 'toBeBetween(from, to)' +description: 'Use toBeBetween(from, to) to check if numeric value is within range.' +excerpt: 'Use toBeBetween(from, to) to check if numeric value is within range.' +--- + +`toBeBetween(from, to)` is a comparison function that evaluates to true or false. It must be called in the chain after the `t.expect(value)` or `.and(value)`. + +`toBeBetween(from, to)` is equivalent to `value >= from && value <= to` + +When `toBeBetween(from, to)` evaluates to false, the chain is broken, and the test case is marked as failed. When the chain is broken, further checks inside of the `test` are omitted. + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| from | Number | Beginning of the range (inclusive) | +| to | Number | End of the range (inclusive) | + + +### Returns + +| Type | Description | +| ------ | ------------------------------- | +| Funk | Funk object | + +### Example + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + + describe('Basic API test', (t) => { + let response = http.get("https://test-api.k6.io/public/crocodiles") + + t.expect(response.status).as("response status").toBeBetween(200, 299); + }) +} +``` + + + +When you run this test with `k6 run mytest.js` the result should look similar to this: + +``` +█ Basic API test + ✓ response status is between 200 - 299 +``` + + \ No newline at end of file diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/36 toBeTruthy.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/36 toBeTruthy.md new file mode 100644 index 0000000000..9618d2fba6 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/36 toBeTruthy.md @@ -0,0 +1,46 @@ +--- +title: 'toBeTruthy()' +description: 'Use toBeTruthy() to check that the value is truthy.' +excerpt: 'Use toBeTruthy() to check that the value is truthy.' +--- + +`toBeTruthy()` is a comparison function that evaluates to true or false. It must be called in the chain after the `t.expect(value)` or `.and(value)`. + +When `toBeTruthy()` evaluates to false, the chain is broken, and the test is marked as failed. When the chain is broken, further checks inside of the `test` are omitted. + + +### Returns + +| Type | Description | +| ------ | ------------------------------- | +| Funk | Funk object | + +### Example + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + + describe('Basic test', (t) => { + t.expect(1).toBeTruthy(); // true + t.expect("hello").toBeTruthy(); // true + t.expect(3.14).toBeTruthy(); // true + t.expect([]).toBeTruthy(); // true + t.expect({}).toBeTruthy(); // true + t.expect(true).toBeTruthy(); // true + t.expect("1").toBeTruthy(); // true + + t.expect(0).toBeTruthy(); // false + t.expect(undefined).toBeTruthy(); // false + t.expect(NaN).toBeTruthy(); // false + t.expect(false).toBeTruthy(); // false + t.expect("").toBeTruthy(); // false + }) +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/40 toHaveValidJson.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/40 toHaveValidJson.md new file mode 100644 index 0000000000..6778cd5ae3 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/40 toHaveValidJson.md @@ -0,0 +1,36 @@ +--- +title: 'toHaveValidJson( )' +description: 'Use .expect(response).toHaveValidJson() to check that HTTP response contains valid JSON.' +excerpt: 'Use .expect(response).toHaveValidJson() to check that HTTP response contains valid JSON.' +--- + +`toHaveValidJson()` validates that the http response has valid JSON body. It must be called in the chain after the `t.expect(response)` or `.and(response)`. + +When `toHaveValidJson()` returns false, the chain is broken, and the test is marked as failed. When the chain is broken, further checks inside of the `test` are omitted. + + +### Returns + +| Type | Description | +| ------ | ------------------------------- | +| Funk | Funk object | + +### Example + + + +```javascript +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; +import http from 'k6/http'; + +export default function testSuite() { + describe('Basic test', (t) => { + let response = http.get("https://test-api.k6.io/public/crocodiles") + + t.expect(response).toHaveValidJson() + .and(response.json().length).as("number of crocs").toBeGreaterThan(5); + }) +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/images/exception-handling.png b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/images/exception-handling.png new file mode 100644 index 0000000000..da52928146 Binary files /dev/null and b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/images/exception-handling.png differ diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/images/functional.js-sample-output.png b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/images/functional.js-sample-output.png new file mode 100644 index 0000000000..1cc7f8b198 Binary files /dev/null and b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/images/functional.js-sample-output.png differ diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/images/test-output.png b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/images/test-output.png new file mode 100644 index 0000000000..f988cd2381 Binary files /dev/null and b/src/data/markdown/versioned-js-api/v0.31/11 jslib/expect/images/test-output.png differ diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/09 request(method, url, [body], [params]).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/09 request(method, url, [body], [params]).md new file mode 100644 index 0000000000..14d8cb59f8 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/09 request(method, url, [body], [params]).md @@ -0,0 +1,49 @@ +--- +title: 'request(method, url, [body], [params])' +head_title: 'httpx.request()' +description: 'Generic method for making arbitrary HTTP requests' +excerpt: 'Generic method for making arbitrary HTTP requests' +--- + +Generic method for making arbitrary HTTP requests. + +Consider using specific methods for making common requests ([get](/javascript-api/v0-31/jslib/httpx/get-url-body-params), [post](/javascript-api/v0-31/jslib/httpx/post-url-body-params), [put](/javascript-api/v0-31/jslib/httpx/put-url-body-params), [patch](/javascript-api/v0-31/jslib/httpx/patch-url-body-params)) + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| method | string | HTTP method. Note, the method must be uppercase (GET, POST, PUT, PATCH, OPTIONS, HEAD, etc) | +| url | string | HTTP URL. If baseURL is set, provide only path. | +| body (optional) | null / string / object / ArrayBuffer / [SharedArray](/javascript-api/v0-31/k6-data/sharedarray) | Request body; objects will be `x-www-form-urlencoded`. Set to `null` to omit the body. | +| params (optional) | null or object {} | Additional [parameters](/javascript-api/v0-31/k6-http/params) for this specific request. | + + +### Returns + +| Type | Description | +| -------------------------------------------- | --------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.4/index.js'; + +let session = new Httpx({ + baseURL: 'https://httpbin.test.k6.io', + timeout: 20000 // 20s timeout. +}); + +export default function testSuite() { + let resp_get = session.request('GET', `/status/200`); + let resp_post = session.request('POST', `/status/200`, {'key': 'value'}); + let resp_put = session.request('PUT', `/status/200`, {'key': 'value'}); + let resp_patch = session.request('PATCH', `/status/200`, {'key': 'value'}); + let resp_delete = session.request('DELETE', `/status/200`); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/10 get(url, [body], [params]).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/10 get(url, [body], [params]).md new file mode 100644 index 0000000000..3724741a51 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/10 get(url, [body], [params]).md @@ -0,0 +1,39 @@ +--- +title: 'get(url, [body], [params])' +description: 'httpx.get makes GET requests' +excerpt: 'httpx.get makes GET requests' +--- + +`session.get(url, body, params)` makes a GET request. Only the URL parameter is required + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| url | string | HTTP URL. If baseURL is set, provide only path. | +| body (optional) | null / string / object / ArrayBuffer / [SharedArray](/javascript-api/v0-31/k6-data/sharedarray) | Set to `null` to omit the body. | +| params (optional) | null or object {} | Additional [parameters](/javascript-api/v0-31/k6-http/params) for this specific request. | + +### Returns + +| Type | Description | +| -------------------------------------------- | --------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.4/index.js'; + +let session = new Httpx({ + baseURL: 'https://test-api.k6.io', + timeout: 20000 // 20s timeout. +}); + +export default function testSuite() { + let resp = session.get(`/public/crocodiles/`); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/11 post(url, [body], [params]).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/11 post(url, [body], [params]).md new file mode 100644 index 0000000000..9ad1fc4e54 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/11 post(url, [body], [params]).md @@ -0,0 +1,44 @@ +--- +title: 'post(url, [body], [params])' +head_title: 'httpx.post' +description: 'httpx.post makes POST requests' +excerpt: 'httpx.post makes POST requests' +--- + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| url | string | HTTP URL. If baseURL is set, provide only path. | +| body (optional) | null / string / object / ArrayBuffer / [SharedArray](/javascript-api/v0-31/k6-data/sharedarray) | Request body; objects will be `x-www-form-urlencoded`. Set to `null` to omit the body. | +| params (optional) | null or object {} | Additional [parameters](/javascript-api/v0-31/k6-http/params) for this specific request. | + +### Returns + +| Type | Description | +| -------------------------------------------- | --------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.4/index.js'; + +let session = new Httpx({ + baseURL: 'https://test-api.k6.io', + timeout: 20000 // 20s timeout. +}); + +export default function testSuite() { + let resp = session.post(`/user/register/`, { + first_name: 'Mr', + last_name: 'Croco', + username: "my user", + password: "my password", + }); +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/12 put(url, [body], [params]).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/12 put(url, [body], [params]).md new file mode 100644 index 0000000000..dd378a6c56 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/12 put(url, [body], [params]).md @@ -0,0 +1,48 @@ +--- +title: 'put(url, [body], [params])' +head_title: 'httpx.put' +description: 'httpx.put makes PUT requests' +excerpt: 'httpx.put makes PUT requests' +--- + +`session.put(url, body, params)` makes a PUT request. Only the first parameter is required + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| url | string | HTTP URL. If baseURL is set, provide only path. | +| body (optional) | null / string / object / ArrayBuffer / [SharedArray](/javascript-api/v0-31/k6-data/sharedarray) | Request body; objects will be `x-www-form-urlencoded`. Set to `null` to omit the body. | +| params (optional) | null or object {} | Additional [parameters](/javascript-api/v0-31/k6-http/params) for this specific request. | + +### Returns + +| Type | Description | +| -------------------------------------------- | --------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.4/index.js'; + +let session = new Httpx({ + baseURL: 'https://httpbin.test.k6.io', + timeout: 20000 // 20s timeout. +}); + +export default function testSuite() { + let resp = session.put(`/put`, { + first_name: 'Mr', + last_name: 'Croco', + username: "my user", + password: "my password", + }); + console.log(resp.status) +} + +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/13 patch(url, [body], [params]).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/13 patch(url, [body], [params]).md new file mode 100644 index 0000000000..898aa8387d --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/13 patch(url, [body], [params]).md @@ -0,0 +1,47 @@ +--- +title: 'patch(url, [body], [params])' +head_title: 'httpx.patch' +description: 'httpx.patch makes PATCH requests' +excerpt: 'httpx.patch makes PATCH requests' +--- + +`session.patch(url, body, params)` makes a PATCH request. Only the first parameter is required + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| url | string | HTTP URL. If baseURL is set, provide only path. | +| body (optional) | null / string / object / ArrayBuffer / [SharedArray](/javascript-api/v0-31/k6-data/sharedarray) | Request body; objects will be `x-www-form-urlencoded`. Set to `null` to omit the body. | +| params (optional) | null or object {} | Additional [parameters](/javascript-api/v0-31/k6-http/params) for this specific request. | + +### Returns + +| Type | Description | +| -------------------------------------------- | --------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.4/index.js'; + +let session = new Httpx({ + baseURL: 'https://httpbin.test.k6.io', + timeout: 20000 // 20s timeout. +}); + +export default function testSuite() { + let resp = session.patch(`/patch`, { + first_name: 'Mr', + last_name: 'Croco', + username: "my user", + password: "my password", + }); +} + +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/14 delete(url, [body], [params]).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/14 delete(url, [body], [params]).md new file mode 100644 index 0000000000..f1e5792625 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/14 delete(url, [body], [params]).md @@ -0,0 +1,41 @@ +--- +title: 'delete(url, [body], [params])' +description: 'httpx.delete makes DELETE requests' +excerpt: 'httpx.delete makes DELETE requests' +--- + +`session.delete(url, body, params)` makes a DELETE request. Only the first parameter is required. Body is discouraged. + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| url | string | HTTP URL. If baseURL is set, provide only path. | +| body (optional) | null / string / object / ArrayBuffer / [SharedArray](/javascript-api/v0-31/k6-data/sharedarray) | Request body; objects will be `x-www-form-urlencoded`. Set to `null` to omit the body. | +| params (optional) | null or object {} | Additional [parameters](/javascript-api/v0-31/k6-http/params) for this specific request. | + +### Returns + +| Type | Description | +| -------------------------------------------- | --------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.4/index.js'; + +let session = new Httpx({ + baseURL: 'https://httpbin.test.k6.io', + timeout: 20000 // 20s timeout. +}); + +export default function testSuite() { + let resp = session.delete(`/delete`); +} + +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/15 options(url, [body], [params]).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/15 options(url, [body], [params]).md new file mode 100644 index 0000000000..0ea67931e3 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/15 options(url, [body], [params]).md @@ -0,0 +1,42 @@ +--- +title: 'options(url, [body], [params])' +description: 'httpx.options makes OPTIONS requests' +excerpt: 'httpx.options makes OPTIONS requests' +--- + +`session.options(url, body, params)` makes an OPTIONS request. Only the first parameter is required + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| url | string | HTTP URL. If baseURL is set, provide only path. | +| body (optional) | null / string / object / ArrayBuffer / [SharedArray](/javascript-api/v0-31/k6-data/sharedarray) | Request body; objects will be `x-www-form-urlencoded`. Set to `null` to omit the body. | +| params (optional) | null or object {} | Additional [parameters](/javascript-api/v0-31/k6-http/params) for this specific request. | + +### Returns + +| Type | Description | +| -------------------------------------------- | --------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.4/index.js'; + +let session = new Httpx({ + baseURL: 'https://httpbin.test.k6.io', + timeout: 20000 // 20s timeout. +}); + +export default function testSuite() { + let resp = session.options(`/options`); + console.log(resp.status) +} + +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/16 head(url, [body], [params]).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/16 head(url, [body], [params]).md new file mode 100644 index 0000000000..e1e4566487 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/16 head(url, [body], [params]).md @@ -0,0 +1,42 @@ +--- +title: 'head(url, [body], [params])' +description: 'httpx.head makes HEAD requests' +excerpt: 'httpx.head makes HEAD requests' +--- + +`session.head(url, body, params)` makes a HEAD request. Only the first parameter is required + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| url | string | HTTP URL. If baseURL is set, provide only path. | +| body (optional) | null / string / object / ArrayBuffer / [SharedArray](/javascript-api/v0-31/k6-data/sharedarray) | Request body; objects will be `x-www-form-urlencoded`. Set to `null` to omit the body. | +| params (optional) | null or object {} | Additional [parameters](/javascript-api/v0-31/k6-http/params) for this specific request. | + +### Returns + +| Type | Description | +| -------------------------------------------- | --------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.4/index.js'; + +let session = new Httpx({ + baseURL: 'https://httpbin.test.k6.io', + timeout: 20000 // 20s timeout. +}); + +export default function testSuite() { + let resp = session.head(`/head`); + console.log(resp.status) +} + +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/17 trace(url, [body], [params]).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/17 trace(url, [body], [params]).md new file mode 100644 index 0000000000..dbe51e817f --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/17 trace(url, [body], [params]).md @@ -0,0 +1,42 @@ +--- +title: 'trace(url, [body], [params])' +description: 'httpx.trace makes TRACE requests' +excerpt: 'httpx.trace makes TRACE requests' +--- + +`session.trace(url, body, params)` makes a TRACE request. Only the first parameter is required + + +| Parameter | Type | Description | +| -------------- | ------ | ------------------------------------------------------------------------------------ | +| url | string | HTTP URL. If baseURL is set, provide only path. | +| body (optional) | null / string / object / ArrayBuffer / [SharedArray](/javascript-api/v0-31/k6-data/sharedarray) | Request body; objects will be `x-www-form-urlencoded`. Set to `null` to omit the body. | +| params (optional) | null or object {} | Additional [parameters](/javascript-api/v0-31/k6-http/params) for this specific request. | + +### Returns + +| Type | Description | +| -------------------------------------------- | --------------------- | +| [Response](/javascript-api/v0-31/k6-http/response) | HTTP [Response](/javascript-api/v0-31/k6-http/response) object. | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.4/index.js'; + +let session = new Httpx({ + baseURL: 'https://httpbin.test.k6.io', + timeout: 20000 // 20s timeout. +}); + +export default function testSuite() { + let resp = session.trace(`/trace`); + console.log(resp.status) +} + +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/19 batch(requests).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/19 batch(requests).md new file mode 100644 index 0000000000..e219a7781a --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/19 batch(requests).md @@ -0,0 +1,53 @@ +--- +title: 'batch( requests )' +head_title: 'httpx.batch(requests)' +description: 'Issue multiple HTTP requests in parallel (like e.g. browsers tend to do).' +excerpt: 'Issue multiple HTTP requests in parallel (like e.g. browsers tend to do).' +--- + +Batch multiple HTTP requests together, to issue them in parallel over multiple TCP connections. + +| Parameter | Type | Description | +| --------- | --------------- | ---------------------------------------------------------------- | +| requests | array | An array containing requests, in string or object form | +| params (optional) | object | additional parameters for all requests in the batch | + + +### Returns + +| Type | Description | +| ------ | ------------------- | +| array | An array containing [Response](/javascript-api/v0-31/k6-http/response) objects. | + +### Example + + + +```javascript +import { Httpx, Get } from 'https://jslib.k6.io/httpx/0.0.2/index.js'; +import { describe } from 'https://jslib.k6.io/expect/0.0.4/index.js'; + +let session = new Httpx({ baseURL: 'https://test-api.k6.io' }); + +export default function () { + + describe('01. Fetch public crocodiles all at once', (t) => { + let responses = session.batch([ + new Get('/public/crocodiles/1/'), + new Get('/public/crocodiles/2/'), + new Get('/public/crocodiles/3/'), + new Get('/public/crocodiles/4/'), + ], { + tags: {name: 'PublicCrocs'} + }); + + responses.forEach(response => { + t.expect(response.status).as("response status").toEqual(200) + .and(response).toHaveValidJson() + .and(response.json('age')).as('croc age').toBeGreaterThan(7); + }); + }); +} +``` + + \ No newline at end of file diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/20 setBaseUrl(url).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/20 setBaseUrl(url).md new file mode 100644 index 0000000000..33c3cdd874 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/20 setBaseUrl(url).md @@ -0,0 +1,29 @@ +--- +title: 'setBaseUrl( url )' +description: 'sets the base URL for the session' +excerpt: 'sets the base URL for the session' +--- + + +| Parameter | Type | Description | +| --------- | --------------- | ---------------------------------------------------------------- | +| baseURL | string | Base URL to be used for all requests issued in the session | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.1/index.js'; + +let session = new Httpx(); + +session.setBaseUrl('https://test-api.k6.io'); + +export default function () { + session.get('/public/crocodiles/1/'); // baseUrl doesn't need to be repeated on every request +} +``` + + \ No newline at end of file diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/21 addHeader(key, value).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/21 addHeader(key, value).md new file mode 100644 index 0000000000..ff5bfafc22 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/21 addHeader(key, value).md @@ -0,0 +1,30 @@ +--- +title: 'addHeader( key, value )' +description: 'adds a header to the session' +excerpt: 'adds a header to the session' +--- + + +| Parameter | Type | Description | +| --------- | --------------- | ---------------------------------------------------------------- | +| name | string | Header name | +| value | string | Header value | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.1/index.js'; + +let session = new Httpx({baseURL: 'https://test-api.k6.io'}); + +session.addHeader('Authorization', 'token1'); + +export default function () { + session.get('/public/crocodiles/1/'); +} +``` + + \ No newline at end of file diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/22 addHeaders(object).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/22 addHeaders(object).md new file mode 100644 index 0000000000..ce36564cd6 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/22 addHeaders(object).md @@ -0,0 +1,33 @@ +--- +title: 'addHeaders( object )' +description: 'adds multiple headers to the session' +excerpt: 'adds multiple headers to the session' +--- + + +| Parameter | Type | Description | +| --------- | --------------- | ---------------------------------------------------------------- | +| headers | object | Object | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.1/index.js'; + +let session = new Httpx(); + +session.addHeaders({ + 'Authorization': 'token1', + 'User-Agent': "My custom user agent", + "Content-Type": 'application/x-www-form-urlencoded' +}); + +export default function () { + session.get('https://test-api.k6.io/public/crocodiles/1/'); +} +``` + + \ No newline at end of file diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/23 clearHeader(name).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/23 clearHeader(name).md new file mode 100644 index 0000000000..bdcddfc313 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/23 clearHeader(name).md @@ -0,0 +1,29 @@ +--- +title: 'clearHeader( name )' +description: 'removes header from the session' +excerpt: 'removes header from the session' +--- + + +| Parameter | Type | Description | +| --------- | --------------- | ---------------------------------------------------------------- | +| name | string | Header name to be removed | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.1/index.js'; + +let session = new Httpx({headers: {'Authorization': 'token1'}}); + +session.clearHeader('Authorization'); // removes header set in the constructor + +export default function () { + session.get('https://test-api.k6.io/public/crocodiles/1/'); +} +``` + + \ No newline at end of file diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/24 addTag(key, value).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/24 addTag(key, value).md new file mode 100644 index 0000000000..9fd72552b3 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/24 addTag(key, value).md @@ -0,0 +1,31 @@ +--- +title: 'addTag( key, value )' +description: 'adds a tag to the session' +excerpt: 'adds a tag to the session' +--- + + +| Parameter | Type | Description | +| --------- | --------------- | ---------------------------------------------------------------- | +| name | string | Tag name | +| value | string | Tag value | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.1/index.js'; + +let session = new Httpx({baseURL: 'https://test-api.k6.io'}); + +session.addTag('tagName', 'tagValue'); +session.addTag('AnotherTagName', 'tagValue2'); + +export default function () { + session.get('/public/crocodiles/1/'); +} +``` + + \ No newline at end of file diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/25 addTags(object).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/25 addTags(object).md new file mode 100644 index 0000000000..21e6eaa492 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/25 addTags(object).md @@ -0,0 +1,32 @@ +--- +title: 'addTags( object )' +description: 'adds multiple tags to the session' +excerpt: 'adds multiple tags to the session' +--- + + +| Parameter | Type | Description | +| --------- | --------------- | ---------------------------------------------------------------- | +| headers | object | Object | + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.1/index.js'; + +let session = new Httpx(); + +session.addTags({ + 'Tag1': 'value1', + 'Tag2': 'value2', + 'Tag3': 'value3', +}); + +export default function () { + session.get('https://test-api.k6.io/public/crocodiles/1/'); +} +``` + + \ No newline at end of file diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/26 clearTag(name).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/26 clearTag(name).md new file mode 100644 index 0000000000..d5efc75e82 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/httpx/26 clearTag(name).md @@ -0,0 +1,29 @@ +--- +title: 'clearTag( name )' +description: 'removes tag from the session' +excerpt: 'removes tag from the session' +--- + + +| Parameter | Type | Description | +| --------- | --------------- | ---------------------------------------------------------------- | +| name | string | Tag name to be removed | + + +### Example + + + +```javascript +import { Httpx } from 'https://jslib.k6.io/httpx/0.0.1/index.js'; + +let session = new Httpx({tags: {'tagName': 'tagValue'}}); + +session.clearTag('tagName'); // removes tag set in the constructor + +export default function () { + session.get('https://test-api.k6.io/public/crocodiles/1/'); +} +``` + + \ No newline at end of file diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/01 randomIntBetween(min, max) copy.md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/01 randomIntBetween(min, max) copy.md new file mode 100644 index 0000000000..32eaa2034c --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/01 randomIntBetween(min, max) copy.md @@ -0,0 +1,37 @@ +--- +title: 'randomIntBetween(min, max)' +description: 'Random integer' +excerpt: 'Random integer' +--- + +Function returns a random number between the specified range. The returned value is no lower than (and may possibly equal) min, and is no bigger than (and may possibly equal) max. + +| Parameter | Type | Description | +| -------------- | ------ | --- | +| min | int | Lower-end bound. Inclusive | +| max | int | Upper-end bound. Inclusive| + + +### Returns + +| Type | Description | +| ----- | --------------- | +| int | Random integer | + + +### Example + + + +```javascript +import { sleep } from 'k6'; +import { randomIntBetween } from "https://jslib.k6.io/k6-utils/1.1.0/index.js"; + +export default function() { + // code ... + + sleep(randomIntBetween(1, 5)); // sleep between 1 and 5 seconds. +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/02 randomItem(array).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/02 randomItem(array).md new file mode 100644 index 0000000000..370053ab3f --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/02 randomItem(array).md @@ -0,0 +1,36 @@ +--- +title: 'randomItem(array)' +description: 'Random item from an array' +excerpt: 'Random item from an array' +--- + +Function returns a random item from an array. + +| Parameter | Type | Description | +| ------------- | ------ | --- | +| arrayOfItems | array | Array [] of items | + + +### Returns + +| Type | Description | +| ----- | --------------- | +| any | Random item from the array | + + +### Example + + + +```javascript +import { randomItem } from "https://jslib.k6.io/k6-utils/1.1.0/index.js"; + +let names = ['John', 'Jane', 'Bert', 'Ed']; + +export default function() { + let randomName = randomItem(names); + console.log(`Hello, my name is ${randomName}`) +} +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/03 randomString(length).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/03 randomString(length).md new file mode 100644 index 0000000000..fa77f1f66c --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/03 randomString(length).md @@ -0,0 +1,35 @@ +--- +title: 'randomString(length)' +description: 'Random string' +excerpt: 'Random string' +--- + +Function returns a random string of a given length. + +| Parameter | Type | Description | +| ------------- | ------ | --- | +| length | int | Length of the random string | + + +### Returns + +| Type | Description | +| ----- | --------------- | +| any | Random item from the array | + + +### Example + + + +```javascript +import { randomString } from "https://jslib.k6.io/k6-utils/1.1.0/index.js"; + +export default function() { + let randomName = randomString(8); + console.log(`Hello, my name is ${randomName}`) +} + +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/04 uuidv4().md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/04 uuidv4().md new file mode 100644 index 0000000000..90c76df171 --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/04 uuidv4().md @@ -0,0 +1,30 @@ +--- +title: 'uuidv4()' +description: 'uuid v4 function' +excerpt: 'uuid v4 function' +--- + +Function returns a random uuid v4 in a string form. + +### Returns + +| Type | Description | +| ----- | --------------- | +| string | Random UUID v4 string | + + +### Example + + + +```javascript +import { uuidv4 } from "https://jslib.k6.io/k6-utils/1.1.0/index.js"; + +export default function() { + let randomUUID = uuidv4(); + console.log(randomUUID); // 35acae14-f7cb-468a-9866-1fc45713149a +} + +``` + + diff --git a/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/05 findBetween(content, left, right).md b/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/05 findBetween(content, left, right).md new file mode 100644 index 0000000000..5bc90d819a --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/11 jslib/utils/05 findBetween(content, left, right).md @@ -0,0 +1,38 @@ +--- +title: 'findBetween(content, left, right)' +description: 'findBetween function' +excerpt: 'findBetween function' +--- + +Function that returns a string from between two other strings. + +| Parameter | Type | Description | +| ------------- | ------ | --- | +| content | string | The string to search through (e.g. [Response.body](https://k6.io/docs/javascript-api/v0-31/k6-http/response/)) | +| left | string | The string immediately before the value to be extracted | +| right | string | The string immediately after the value to be extracted | + +### Returns + +| Type | Description | +| ----- | --------------- | +| string | The extracted string, or an empty string if no match was found | + + +### Example + + + +```javascript +import { findBetween } from "https://jslib.k6.io/k6-utils/1.1.0/index.js"; + +export default function() { + const response = '
Login successful!
'; + + const message = findBetween(response, '
', '
'); + + console.log(message); // Login successful! +} +``` + +
diff --git a/src/data/markdown/versioned-js-api/v0.31/99 Error Codes.md b/src/data/markdown/versioned-js-api/v0.31/99 Error Codes.md new file mode 100644 index 0000000000..e7a7b566fb --- /dev/null +++ b/src/data/markdown/versioned-js-api/v0.31/99 Error Codes.md @@ -0,0 +1,48 @@ +--- +title: 'Error Codes' +excerpt: 'Error codes are unique numbers that can be used to identify and handle different application and network errors more easily.' +--- + +Error codes are unique numbers that can be used to identify and handle different application and network errors more easily. For the moment, these error codes are applicable only for errors that happen during HTTP requests, but they will be reused and extended to support other protocols in future k6 releases. + +When an error occurs, its code is determined and returned as both the `error_code` field of the [`http.Response`](/javascript-api/v0-31/k6-http/response) object, and also attached as the `error_code` [tag](/using-k6/tags-and-groups) to any [metrics](/using-k6/metrics) associated with that request. Additionally, for more details, the `error` metric tag and `http.Response` field will still contain the actual string error message. + +Error codes for different errors are as distinct as possible, but for easier handling and grouping, codes in different error categories are also grouped in broad ranges. The current error code ranges are: + +- 1000-1099 - General errors +- 1100-1199 - DNS errors +- 1200-1299 - TCP errors +- 1300-1399 - TLS errors +- 1400-1499 - HTTP 4xx errors +- 1500-1599 - HTTP 5xx errors +- 1600-1699 - HTTP/2 specific errors + +The following specific error codes are currently defined: + +- 1000: A generic error that isn't any of the ones listed below. +- 1010: A non-TCP network error - this is a place holder there is no error currently known to trigger it. +- 1100: A generic DNS error that isn't any of the ones listed below. +- 1101: No IP for the provided host was found. +- 1110: Blacklisted IP was resolved or a connection to such was tried to be established. +- 1111: Blacklisted hostname using The [Block Hostnames](/using-k6/options#block-hostnames) option. +- 1200: A generic TCP error that isn't any of the ones listed below. +- 1201: A "broken pipe" on write - the other side has likely closed the connection. +- 1202: An unknown TCP error - We got an error that we don't recognize but it is from the operating system and has `errno` set on it. The message in `error` includes the operation(write,read) and the errno, the OS, and the original message of the error. +- 1210: General TCP dial error. +- 1211: Dial timeout error - the timeout for the dial was reached. +- 1212: Dial connection refused - the connection was refused by the other party on dial. +- 1213: Dial unknown error. +- 1220: Reset by peer - the connection was reset by the other party, most likely a server. +- 1300: General TLS error +- 1310: Unknown authority - the certificate issuer is unknown. +- 1311: The certificate doesn't match the hostname. +- 1400 to 1499: error codes that correspond to the [HTTP 4xx status codes for client errors](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_errors) +- 1500 to 1599: error codes that correspond to the [HTTP 5xx status codes for server errors](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_errors) +- 1600: A generic HTTP/2 error that isn't any of the ones listed below. +- 1610: A general HTTP/2 GoAway error. +- 1611 to 1629: HTTP/2 GoAway errors with the value of the specific [HTTP/2 error code](https://tools.ietf.org/html/rfc7540#section-7) added to 1611. +- 1630: A general HTTP/2 stream error. +- 1631 to 1649: HTTP/2 stream errors with the value of the specific [HTTP/2 error code](https://tools.ietf.org/html/rfc7540#section-7) added to 1631. +- 1650: A general HTTP/2 connection error. +- 1651 to 1669: HTTP/2 connection errors with the value of the specific [HTTP/2 error code](https://tools.ietf.org/html/rfc7540#section-7) added to 1651. +- 1701: Decompression error. diff --git a/src/layouts/doc-layout/doc-layout.module.scss b/src/layouts/doc-layout/doc-layout.module.scss index fecfb1a438..7faa466a5b 100644 --- a/src/layouts/doc-layout/doc-layout.module.scss +++ b/src/layouts/doc-layout/doc-layout.module.scss @@ -217,3 +217,20 @@ a.sidebar-link { } } } + +.versionSwitcher { + margin-right: 15px; + margin-left: auto; + + @include md-down { + margin-left: 0; + margin-top: 20px; + } + + &-mobile { + @include sm-down { + margin-top: 0; + margin-right: auto; + } + } +} diff --git a/src/layouts/doc-layout/doc-layout.view.js b/src/layouts/doc-layout/doc-layout.view.js index 1c817f83f3..1990d0d09e 100644 --- a/src/layouts/doc-layout/doc-layout.view.js +++ b/src/layouts/doc-layout/doc-layout.view.js @@ -13,6 +13,8 @@ import HelperWidget from 'components/shared/helper-widget'; import { LanguageSwitcher } from 'components/shared/language-switcher'; import { SearchBox } from 'components/shared/search-box'; import { SEO } from 'components/shared/seo'; +import { VersionBanner } from 'components/shared/version-banner'; +import { VersionSwitcher } from 'components/shared/version-switcher'; import { useLocale } from 'contexts/locale-provider'; import { Link, navigate, withPrefix } from 'gatsby'; import { I18N_CONFIG } from 'i18n/i18n-config'; @@ -25,6 +27,7 @@ import { import { childrenToList, slugify, isInIFrame } from 'utils'; import AlgoliaQueries from 'utils/algolia'; import { main, app } from 'utils/urls'; +import { LATEST_VERSION } from 'utils/versioning'; import styles from './doc-layout.module.scss'; @@ -223,9 +226,11 @@ const SidebarNode = (props) => { export const DocLayout = ({ pageMetadata, pageTranslations = null, + version, sidebarTree, navLinks: links, children, + pageVersions = null, }) => { const [isMobileNavVisible, setIsMobileNavVisible] = useState(false); const [showFooter, setShowFooter] = useState(true); @@ -270,7 +275,11 @@ export const DocLayout = ({ return (
- +
@@ -281,6 +290,13 @@ export const DocLayout = ({ className={styles.languageSwitcher} /> )} + {!!version && ( + + )}
{sidebarTree && childrenToList(sidebarTree.children).map((sectionNode) => ( @@ -341,6 +357,16 @@ export const DocLayout = ({ )} /> )} + {!!version && ( + + )} setIsMobileNavVisible(true)} />
@@ -355,6 +381,9 @@ export const DocLayout = ({
+ {version && version !== LATEST_VERSION && ( + + )} {children} = 0; + return ( -
+
= 0 : false; + return (
diff --git a/src/templates/docs/javascript-api.js b/src/templates/docs/javascript-api.js index 1ff36a2bff..d22fbc43c8 100644 --- a/src/templates/docs/javascript-api.js +++ b/src/templates/docs/javascript-api.js @@ -16,6 +16,7 @@ import { DocLayout } from 'layouts/doc-layout'; import React, { useRef } from 'react'; import { Sticky, StickyContainer } from 'react-sticky'; import SeoMetadata from 'utils/seo-metadata'; +import { LATEST_VERSION, SUPPORTED_VERSIONS } from 'utils/utils.node'; const componentsForNativeReplacement = { table: TableWrapper, @@ -48,7 +49,10 @@ const getContent = (nodes, sidebarTree) => return null; }); -export default function ({ data, pageContext: { sidebarTree, navLinks } }) { +export default function ({ + data, + pageContext: { sidebarTree, navLinks, version = LATEST_VERSION }, +}) { const content = getContent(data.allFile.nodes, sidebarTree); const pageMetadata = SeoMetadata['javascript-api']; const contentContainerRef = useRef(null); @@ -59,16 +63,28 @@ export default function ({ data, pageContext: { sidebarTree, navLinks } }) { docPageContent.contentWrapper, ); + const pageVersions = {}; + pageVersions[LATEST_VERSION] = { path: '/javascript-api/' }; + SUPPORTED_VERSIONS.forEach((version) => { + pageVersions[version] = { + path: `/javascript-api/${version.replace(/\./g, '-')}/`, + }; + }); + return (
diff --git a/src/utils/utils.js b/src/utils/utils.js index 77c3dee2b7..f0dd4056db 100644 --- a/src/utils/utils.js +++ b/src/utils/utils.js @@ -76,6 +76,8 @@ const stripDirectoryPath = (str, type) => { return str.replace(/^.*docs\/(.*)$/, '$1'); case 'guides': return str.replace(/^.*guides\/(.*)$/, '$1'); + case 'javascript-api': + return str.replace(/^.*js-api\/(.*)$/, '$1'); case 'post': return str.replace(/(.*)(\d{4}-\d{2}-\d{2}.*)(\/.*\.\w+$)/, '$2'); default: diff --git a/src/utils/utils.node.js b/src/utils/utils.node.js index 0662f295e2..53ad81a503 100644 --- a/src/utils/utils.node.js +++ b/src/utils/utils.node.js @@ -2,6 +2,7 @@ const { pathTranslations } = require('../i18n/path-translations'); const { slugify, compose, stripDirectoryPath } = require('./utils'); +const { SUPPORTED_VERSIONS, LATEST_VERSION } = require('./versioning'); const SUPPORTED_LOCALES = ['es', 'en']; const DEFAULT_LOCALE = 'en'; @@ -34,7 +35,7 @@ const translatePath = (path, locale) => .join('/'); // buildBreadcrumbs(path: String) -> Array -const buildBreadcrumbs = (path) => { +const buildBreadcrumbs = (path, versioned = false) => { let accumulatedPath = ''; return path.split('/').map((part, i) => { accumulatedPath += `/${part}`; @@ -46,6 +47,8 @@ const buildBreadcrumbs = (path) => { : part.slice(0, 1).toUpperCase() + part.slice(1); } else if (i === 1) { name = new RegExp(/k6-/i).test(part) ? part.replace(/-/g, '/') : part; + } else if (i === 2 && versioned) { + name = new RegExp(/k6-/i).test(part) ? part.replace(/-/g, '/') : part; } else { name = part; } @@ -304,6 +307,12 @@ Object.defineProperties(utils, { getTranslatedSlug: { value: getTranslatedSlug, }, + SUPPORTED_VERSIONS: { + value: SUPPORTED_VERSIONS, + }, + LATEST_VERSION: { + value: LATEST_VERSION, + }, }); module.exports = utils; diff --git a/src/utils/versioning.js b/src/utils/versioning.js new file mode 100644 index 0000000000..f01cb959d0 --- /dev/null +++ b/src/utils/versioning.js @@ -0,0 +1,6 @@ +/** version number for which documentation is available (except for the latest version) */ +const SUPPORTED_VERSIONS = ['v0.31']; +/** latest version number for URLs without version prefix */ +const LATEST_VERSION = 'v0.32'; + +module.exports = { SUPPORTED_VERSIONS, LATEST_VERSION };