How to use noBodyStatus method in wpt

Best JavaScript code snippet using wpt

http-cache.js

Source:http-cache.js Github

copy

Full Screen

1/* global btoa fetch token promise_test step_timeout */2/* global assert_equals assert_true assert_own_property assert_throws assert_less_than */3const templates = {4 'fresh': {5 'response_headers': [6 ['Expires', 100000],7 ['Last-Modified', 0]8 ]9 },10 'stale': {11 'response_headers': [12 ['Expires', -5000],13 ['Last-Modified', -100000]14 ]15 },16 'lcl_response': {17 'response_headers': [18 ['Location', 'location_target'],19 ['Content-Location', 'content_location_target']20 ]21 },22 'location': {23 'query_arg': 'location_target',24 'response_headers': [25 ['Expires', 100000],26 ['Last-Modified', 0]27 ]28 },29 'content_location': {30 'query_arg': 'content_location_target',31 'response_headers': [32 ['Expires', 100000],33 ['Last-Modified', 0]34 ]35 }36}37const noBodyStatus = new Set([204, 304])38function makeTest (test) {39 return function () {40 var uuid = token()41 var requests = expandTemplates(test)42 var fetchFunctions = []43 for (let i = 0; i < requests.length; ++i) {44 fetchFunctions.push({45 code: function (idx) {46 var config = requests[idx]47 var url = makeTestUrl(uuid, config)48 var init = fetchInit(requests, config)49 return fetch(url, init)50 .then(makeCheckResponse(idx, config))51 .then(makeCheckResponseBody(config, uuid), function (reason) {52 if ('expected_type' in config && config.expected_type === 'error') {53 assert_throws(new TypeError(), function () { throw reason })54 } else {55 throw reason56 }57 })58 },59 pauseAfter: 'pause_after' in requests[i]60 })61 }62 var idx = 063 function runNextStep () {64 if (fetchFunctions.length) {65 var nextFetchFunction = fetchFunctions.shift()66 if (nextFetchFunction.pauseAfter === true) {67 return nextFetchFunction.code(idx++)68 .then(pause)69 .then(runNextStep)70 } else {71 return nextFetchFunction.code(idx++)72 .then(runNextStep)73 }74 } else {75 return Promise.resolve()76 }77 }78 return runNextStep()79 .then(function () {80 return getServerState(uuid)81 }).then(function (testState) {82 checkRequests(requests, testState)83 return Promise.resolve()84 })85 }86}87function expandTemplates (test) {88 var rawRequests = test.requests89 var requests = []90 for (let i = 0; i < rawRequests.length; i++) {91 var request = rawRequests[i]92 request.name = test.name93 if ('template' in request) {94 var template = templates[request['template']]95 for (let member in template) {96 if (!request.hasOwnProperty(member)) {97 request[member] = template[member]98 }99 }100 }101 requests.push(request)102 }103 return requests104}105function fetchInit (requests, config) {106 var init = {107 'headers': []108 }109 if ('request_method' in config) init.method = config['request_method']110 if ('request_headers' in config) init.headers = config['request_headers']111 if ('name' in config) init.headers.push(['Test-Name', config.name])112 if ('request_body' in config) init.body = config['request_body']113 if ('mode' in config) init.mode = config['mode']114 if ('credentials' in config) init.mode = config['credentials']115 if ('cache' in config) init.cache = config['cache']116 init.headers.push(['Test-Requests', btoa(JSON.stringify(requests))])117 return init118}119function makeCheckResponse (idx, config) {120 return function checkResponse (response) {121 var reqNum = idx + 1122 var resNum = parseInt(response.headers.get('Server-Request-Count'))123 if ('expected_type' in config) {124 if (config.expected_type === 'error') {125 assert_true(false, `Request ${reqNum} doesn't throw an error`)126 return response.text()127 }128 if (config.expected_type === 'cached') {129 assert_less_than(resNum, reqNum, `Response ${reqNum} does not come from cache`)130 }131 if (config.expected_type === 'not_cached') {132 assert_equals(resNum, reqNum, `Response ${reqNum} comes from cache`)133 }134 }135 if ('expected_status' in config) {136 assert_equals(response.status, config.expected_status,137 `Response ${reqNum} status is ${response.status}, not ${config.expected_status}`)138 } else if ('response_status' in config) {139 assert_equals(response.status, config.response_status[0],140 `Response ${reqNum} status is ${response.status}, not ${config.response_status[0]}`)141 } else {142 assert_equals(response.status, 200, `Response ${reqNum} status is ${response.status}, not 200`)143 }144 if ('response_headers' in config) {145 config.response_headers.forEach(function (header) {146 if (header.len < 3 || header[2] === true) {147 assert_equals(response.headers.get(header[0]), header[1],148 `Response ${reqNum} header ${header[0]} is "${response.headers.get(header[0])}", not "${header[1]}"`)149 }150 })151 }152 if ('expected_response_headers' in config) {153 config.expected_response_headers.forEach(function (header) {154 assert_equals(response.headers.get(header[0]), header[1],155 `Response ${reqNum} header ${header[0]} is "${response.headers.get(header[0])}", not "${header[1]}"`)156 })157 }158 return response.text()159 }160}161function makeCheckResponseBody (config, uuid) {162 return function checkResponseBody (resBody) {163 var statusCode = 200164 if ('response_status' in config) {165 statusCode = config.response_status[0]166 }167 if ('expected_response_text' in config) {168 if (config.expected_response_text !== null) {169 assert_equals(resBody, config.expected_response_text,170 `Response body is "${resBody}", not expected "${config.expected_response_text}"`)171 }172 } else if ('response_body' in config && config.response_body !== null) {173 assert_equals(resBody, config.response_body,174 `Response body is "${resBody}", not sent "${config.response_body}"`)175 } else if (!noBodyStatus.has(statusCode)) {176 assert_equals(resBody, uuid, `Response body is "${resBody}", not default "${uuid}"`)177 }178 }179}180function checkRequests (requests, testState) {181 var testIdx = 0182 for (let i = 0; i < requests.length; ++i) {183 var expectedValidatingHeaders = []184 var config = requests[i]185 var serverRequest = testState[testIdx]186 var reqNum = i + 1187 if ('expected_type' in config) {188 if (config.expected_type === 'cached') continue // the server will not see the request189 if (config.expected_type === 'etag_validated') {190 expectedValidatingHeaders.push('if-none-match')191 }192 if (config.expected_type === 'lm_validated') {193 expectedValidatingHeaders.push('if-modified-since')194 }195 }196 testIdx++197 expectedValidatingHeaders.forEach(vhdr => {198 assert_own_property(serverRequest.request_headers, vhdr,199 `request ${reqNum} doesn't have ${vhdr} header`)200 })201 if ('expected_request_headers' in config) {202 config.expected_request_headers.forEach(expectedHdr => {203 assert_equals(serverRequest.request_headers[expectedHdr[0].toLowerCase()], expectedHdr[1],204 `request ${reqNum} header ${expectedHdr[0]} value is "${serverRequest.request_headers[expectedHdr[0].toLowerCase()]}", not "${expectedHdr[1]}"`)205 })206 }207 }208}209function pause () {210 return new Promise(function (resolve, reject) {211 step_timeout(function () {212 return resolve()213 }, 3000)214 })215}216function makeTestUrl (uuid, config) {217 var arg = ''218 if ('query_arg' in config) {219 arg = `&target=${config.query_arg}`220 }221 return `resources/http-cache.py?dispatch=test&uuid=${uuid}${arg}`222}223function getServerState (uuid) {224 return fetch(`resources/http-cache.py?dispatch=state&uuid=${uuid}`)225 .then(function (response) {226 return response.text()227 }).then(function (text) {228 return JSON.parse(text) || []229 })230}231function run_tests (tests) {232 tests.forEach(function (test) {233 promise_test(makeTest(test), test.name)234 })235}236var contentStore = {}237function http_content (csKey) {238 if (csKey in contentStore) {239 return contentStore[csKey]240 } else {241 var content = btoa(Math.random() * Date.now())242 contentStore[csKey] = content243 return content244 }...

Full Screen

Full Screen

handle-test.mjs

Source:handle-test.mjs Github

copy

Full Screen

1import { noBodyStatus } from '../lib/defines.mjs'2import { fixupHeader } from '../lib/header-fixup.mjs'3import { sendResponse, getHeader, configs, stash, setStash, logRequest, logResponse } from './utils.mjs'4export default function handleTest (pathSegs, request, response) {5 // identify the desired configuration for this request6 const uuid = pathSegs[0]7 if (!uuid) {8 sendResponse(response, 404, `Config Not Found for ${uuid}`)9 return10 }11 const requests = configs.get(uuid)12 if (!requests) {13 sendResponse(response, 409, `Requests not found for ${uuid}`)14 return15 }16 const serverState = stash.get(uuid) || []17 const srvReqNum = serverState.length + 118 const cliReqNum = parseInt(request.headers['req-num'])19 const reqNum = cliReqNum || srvReqNum20 const reqConfig = requests[reqNum - 1]21 const previousConfig = requests[reqNum - 2]22 const now = Date.now()23 if (!reqConfig) {24 sendResponse(response, 409, `${requests[0].id} config not found for request ${srvReqNum} (anticipating ${requests.length})`)25 return26 }27 if (reqConfig.dump) logRequest(request, srvReqNum)28 // Determine what the response status should be29 let httpStatus = reqConfig.response_status || [200, 'OK']30 if ('expected_type' in reqConfig && reqConfig.expected_type.endsWith('validated')) {31 const previousLm = getHeader(previousConfig.response_headers, 'Last-Modified')32 if (previousLm && request.headers['if-modified-since'] === previousLm) {33 httpStatus = [304, 'Not Modified']34 }35 const previousEtag = getHeader(previousConfig.response_headers, 'ETag')36 if (previousEtag && request.headers['if-none-match'] === previousEtag) {37 httpStatus = [304, 'Not Modified']38 }39 if (httpStatus[0] !== 304) {40 httpStatus = [999, '304 Not Generated']41 }42 }43 response.statusCode = httpStatus[0]44 response.statusPhrase = httpStatus[1]45 // header manipulation46 const responseHeaders = reqConfig.response_headers || []47 const savedHeaders = new Map()48 response.setHeader('Server-Base-Url', request.url)49 response.setHeader('Server-Request-Count', srvReqNum)50 response.setHeader('Client-Request-Count', cliReqNum)51 response.setHeader('Server-Now', now, 0)52 response.setHeader('Capability-Seen', request.headers['surrogate-capability'] || '')53 responseHeaders.forEach(header => {54 header = fixupHeader(header, response.getHeaders(), reqConfig)55 if (response.hasHeader(header[0])) {56 const currentVal = response.getHeader(header[0])57 if (typeof currentVal === 'string') {58 response.setHeader(header[0], [currentVal, header[1]])59 } else if (Array.isArray(currentVal)) {60 response.setHeader(header[0], currentVal.concat(header[1]))61 } else {62 console.log(`ERROR: Unanticipated header type of ${typeof currentVal} for ${header[0]}`)63 }64 } else {65 response.setHeader(header[0], header[1])66 }67 if (header.length < 3 || header[2] === true) {68 savedHeaders.set(header[0], response.getHeader(header[0]))69 }70 })71 if (!response.hasHeader('content-type')) {72 response.setHeader('Content-Type', 'text/plain')73 }74 // stash information about this request for the client75 serverState.push({76 request_num: cliReqNum,77 request_method: request.method,78 request_headers: request.headers,79 response_headers: Array.from(savedHeaders.entries())80 })81 response.setHeader('Request-Numbers', serverState.map(item => item.request_num).join(' '))82 setStash(uuid, serverState)83 // Response body generation84 if ('disconnect' in reqConfig && reqConfig.disconnect) {85 // disconnect now because we want the state86 response.socket.destroy()87 response = 'disconnect'88 } else if (noBodyStatus.has(response.statusCode)) {89 response.end()90 } else {91 const content = reqConfig.response_body || uuid92 response.end(content)93 }94 // logging95 if (reqConfig.dump) logResponse(response, srvReqNum)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9### WebPageTest(url)10### WebPageTest#runTest(url, options, callback)11### WebPageTest#getTestStatus(testId, callback)12### WebPageTest#getTestResults(testId, callback)13### WebPageTest#getLocations(callback)14### WebPageTest#getLocation(location, callback)15### WebPageTest#getTesters(callback)16### WebPageTest#getTesters(location, callback)

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.noBodyStatus(function(err, data) {4 if (err) console.log(err);5 else console.log(data);6});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful