Best JavaScript code snippet using wpt
requestHelper.js
Source:requestHelper.js
...58 * @description è·åresponseä¸çcookie(set-cookie)59 * @param {Object} response60 * @returns {string}61 */62function getResponseCookies(response) {63 let set_cookie = response ? response['headers']['set-cookie'] : '';64 let temp = {};65 if (set_cookie.length > 0) {66 set_cookie.forEach(function (cookie) {67 let cookie_name = cookie.split(';')[0].split('=')[0];68 let cookie_value = cookie.split(';')[0];69 temp[cookie_name] = cookie_value;70 });71 let temp_cookie = [];72 for (let cookie in temp) {73 temp_cookie.push(temp[cookie]);74 }75 return temp_cookie.join(';');76 }77}78/**79 * @description ä»urlå符串ä¸è·åhost80 * @param {String} url81 * @returns {String}82 */83function getHostFormUrl(url) {84 if (!url) {85 return url;86 }87 return urlModel.parse(url).host;88}89/**90 * @description æ´ç请æ±ä¸çåæ°91 * @param {String} url 请æ±çurl92 * @param {String} params post请æ±çåæ°ï¼å¦name=john&pwd=123456&userType=193 * @returns {String} è¿åæåºæ好çæ°æ®ï¼å¦ï¼form=pc&ol=1&ol=2&name=john&pwd=123456&userType=194 */95function formatParams(url, params) {96 if (!url) {97 return url;98 }99 params = params || '';100 let Url = urlModel.parse(url);101 let urlParams = Url.query || '';102 let temp = {};103 let paramArr = [];104 urlParams && urlParams.split('&').forEach(function (p) {105 let n = p.split('=')[0];106 let v = p.split('=')[1];107 temp[n] = temp[n] || [];108 temp[n].push(v);109 });110 params && params.split('&').forEach(function (p) {111 let n = p.split('=')[0];112 let v = p.split('=')[1];113 temp[n] = temp[n] || [];114 temp[n].push(v);115 });116 for (let k in temp) {117 temp[k].sort(function (a, b) {118 return a - b;119 });120 paramArr.push({name: k, value: temp[k]});121 }122 paramArr.sort(function (a, b) {123 return a.name - b.name;124 });125 let tempArr = [];126 paramArr.forEach(function (p) {127 p.value.forEach(function (v) {128 tempArr.push(p.name + '=' + v);129 });130 });131 return tempArr.join('&');132}133/**134 * @description è·åä¸ä¸ªrequestçheaders头135 * @param {String} [host=''] 设置host136 * @param {String} [cookies=''] 设置cookie137 * @returns {{User-Agent: string, Accept: string, Accept-Language: string, Connection: string, Cache-Control: string}}138 */139function setHeaders(host, cookies) {140 let headers = {141 'User-Agent': getRandomAgent(),142 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',143 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',144 'Connection': 'keep-alive',145 'Cache-Control': 'no-cache'146 };147 if (host) {148 headers['Host'] = host;149 }150 if (cookies) {151 headers['Cookie'] = cookies;152 }153 return headers;154}155/**156 * @description å·æ°header157 * @param response158 * @param headers159 * @returns {{headers: *, cookies: string}}160 */161function refreshHeader(response, headers) {162 let newCookies = getResponseCookies(response);163 let oldCookies = headers['Cookie'] || '';164 let temp = {}, arr = [];165 newCookies.split(';').forEach(function (cookieStr) {166 temp[cookieStr.split('=')[0]] = cookieStr;167 });168 oldCookies.split(';').forEach(function (cookieStr) {169 temp[cookieStr.split('=')[0]] = cookieStr;170 });171 for (let c in temp) {172 arr.push(temp[c]);173 }174 headers['Cookie'] = arr.join(';');175 return {headers: headers, cookies: arr.join(';')};176}
cookie.spec.ts
Source:cookie.spec.ts
...112 ).getProxy();113 cookie["title"] = "plop";114 assert.strictEqual(cookie.needSave(), true);115 await cookie.save(this._ctx);116 assert.deepStrictEqual(this._ctx.getResponseCookies()["test"].options, {117 path: "/",118 domain: "test.webda.io",119 httpOnly: true,120 secure: false,121 maxAge: 604800,122 sameSite: "None"123 });124 cookie["title"] = "plop2";125 assert.strictEqual(cookie.needSave(), true);126 // @ts-ignore127 this._ctx.parameters.cookie = {128 maxAge: 3600129 };130 await cookie.save(this._ctx);131 assert.deepStrictEqual(this._ctx.getResponseCookies()["test"].options, {132 path: "/",133 domain: "test.webda.io",134 httpOnly: true,135 secure: false,136 maxAge: 3600,137 sameSite: "Lax"138 });139 }140 @test("bad cookie")141 testBad() {142 this._ctx.getHttpContext().cookies = {143 testor: "badCookie"144 };145 let stub = sinon.stub(this._ctx, "log").callsFake(() => {});146 try {147 new SecureCookie(148 "testor",149 {150 secretOrPublicKey: "plop".repeat(64)151 },152 this._ctx153 );154 assert.strictEqual(stub.getCall(0).args[0], "WARN");155 assert.ok(stub.getCall(0).args[1].match(/Ignoring bad cookie/));156 } finally {157 stub.restore();158 }159 }160 @test("Normal enc/dec") async testEncryption() {161 var cookie = new SecureCookie(162 "test",163 {164 secretOrPublicKey: SECRET165 },166 this._ctx,167 {168 title: "TITLE",169 desc: "DESCRIPTION"170 }171 ).getProxy();172 assert.strictEqual(cookie["title"], "TITLE");173 assert.strictEqual(cookie["desc"], "DESCRIPTION");174 // Force encryption175 // @ts-ignore176 cookie.changed = true;177 await cookie.save(this._ctx);178 let cookies = this._ctx.getResponseCookies();179 let httpContext = this._ctx.getHttpContext();180 httpContext.cookies = httpContext.cookies || {};181 for (let i in cookies) {182 httpContext.cookies[i] = cookies[i].value;183 }184 var cookie2 = new SecureCookie(185 "test",186 {187 secretOrPublicKey: SECRET188 },189 this._ctx190 );191 assert.strictEqual(cookie.title, cookie2.title);192 assert.strictEqual(cookie2.needSave(), false);193 assert.strictEqual(cookie.desc, cookie2.desc);194 }195 196*/197 @test("Bad cookie") async testBadSecret() {198 let ctx = await this.newContext();199 ctx.getHttpContext().cookies = {};200 ctx.getHttpContext().cookies["test"] = "plop";201 let session = await SecureCookie.load("test", ctx, undefined);202 assert.strictEqual(Object.keys(session).length, 0);203 }204 @test205 async cov() {206 let session = await SecureCookie.load("test", new Context(this.webda, undefined, undefined), undefined);207 assert.strictEqual(Object.keys(session).length, 0);208 }209 @test("Oversize cookie") async testOversize() {210 var cookie = new Session().getProxy();211 cookie.identUsed = "PLOP".repeat(3000);212 assert.strictEqual(cookie.isDirty(), true);213 await SecureCookie.save("test", this._ctx, cookie);214 assert.strictEqual(Object.keys(this._ctx.getResponseCookies()).length, 5);215 for (let i = 1; i < 5; i++) {216 const cookie = this._ctx.getResponseCookies()[`test${i > 1 ? i : ""}`];217 assert.strictEqual(cookieSerialize(cookie.name, cookie.value, cookie.options || {}).length, 4096);218 }219 let ctx = await this.newContext();220 let cookies = this._ctx.getResponseCookies();221 ctx.getHttpContext().cookies = {};222 Object.keys(cookies).forEach(k => {223 ctx.getHttpContext().cookies[k] = cookies[k].value;224 });225 await ctx.init();226 assert.strictEqual(ctx.getSession().identUsed, "PLOP".repeat(3000));227 }...
cookie.js
Source:cookie.js
...10 getCookies() {11 if (this.isClient) return document.cookie || ''12 return (this.req && this.req.headers.cookie) || ''13 }14 getResponseCookies() {15 let cookies = this.res.getHeader('Set-Cookie')16 cookies = typeof cookies === 'string' ? [cookies] : cookies17 return cookies || []18 }19 get(name, parser = null) {20 const cookies = Cookie.parse(this.getCookies())21 const value = cookies[name]22 if (parser) return parser(value)23 return value24 }25 set(name = '', value = '', options = { path: '/' }) {26 const parsedValue = typeof value === 'object' ? JSON.stringify(value) : value27 const cookie = Cookie.serialize(name, parsedValue, { domain: this.domain, ...options })28 if (this.isClient) {29 document.cookie = cookie30 return31 }32 const cookies = this.getResponseCookies()33 cookies.push(cookie)34 this.res.setHeader('Set-Cookie', cookies)35 }36 remove(name = '', options = { path: '/' }) {37 this.set(name, '', { ...options, maxAge: -1 })38 }39}40export default (context) => {41 const { req, res, env, store } = context42 const domain = ''43 const cookie = new CookieUniversal({ req, res, domain })44 return {45 get(name) {46 return cookie.get(name)...
Using AI Code Generation
1var wptdriver = require('wptdriver');2var driver = new wptdriver();3var cookies = driver.getResponseCookies();4console.log(cookies);5var wptdriver = require('wptdriver');6var driver = new wptdriver();7var headers = driver.getResponseHeaders();8console.log(headers);9var wptdriver = require('wptdriver');10var driver = new wptdriver();11var cookies = driver.getResponseCookies();12console.log(cookies);13var headers = driver.getResponseHeaders();14console.log(headers);15var wptdriver = require('wptdriver');16var driver = new wptdriver();17var cookies = driver.getResponseCookies();18console.log(cookies);19var headers = driver.getResponseHeaders();20console.log(headers);21var wptdriver = require('wptdriver');22var driver = new wptdriver();23var cookies = driver.getResponseCookies();24console.log(cookies);25var headers = driver.getResponseHeaders();26console.log(headers);27var wptdriver = require('wptdriver');28var driver = new wptdriver();29var cookies = driver.getResponseCookies();30console.log(cookies);31var headers = driver.getResponseHeaders();32console.log(headers);33var wptdriver = require('wptdriver');34var driver = new wptdriver();35var cookies = driver.getResponseCookies();36console.log(cookies);37var headers = driver.getResponseHeaders();38console.log(headers);39var wptdriver = require('wptdriver');40var driver = new wptdriver();41var cookies = driver.getResponseCookies();42console.log(cookies);43var headers = driver.getResponseHeaders();44console.log(headers);
Using AI Code Generation
1var cookies = wpt.getResponseCookies();2console.log(cookies);3var headers = wpt.getResponseHeaders();4console.log(headers);5var body = wpt.getResponseBody();6console.log(body);7var statusCode = wpt.getResponseStatusCode();8console.log(statusCode);9var statusText = wpt.getResponseStatusText();10console.log(statusText);11var requestUrl = wpt.getRequestUrl();12console.log(requestUrl);13var requestMethod = wpt.getRequestMethod();14console.log(requestMethod);15var requestHeaders = wpt.getRequestHeaders();16console.log(requestHeaders);17var requestBody = wpt.getRequestBody();18console.log(requestBody);19var responseTime = wpt.getResponseTime();20console.log(responseTime);21var responseTime = wpt.getResponseTime();22console.log(responseTime);23var responseTime = wpt.getResponseTime();24console.log(responseTime);25var responseTime = wpt.getResponseTime();26console.log(responseTime);27var responseTime = wpt.getResponseTime();28console.log(responseTime);
Using AI Code Generation
1var wpt = require('wpt');2var wptObj = new wpt();3wptObj.getResponseCookies(function(err, data) {4 if(err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10var wpt = require('wpt');11var wptObj = new wpt();12wptObj.setResponseCookies(function(err, data) {13 if(err) {14 console.log(err);15 } else {16 console.log(data);17 }18});19var wpt = require('wpt');20var wptObj = new wpt();21wptObj.getResponseHeaders(function(err, data) {22 if(err) {23 console.log(err);24 } else {25 console.log(data);26 }27});28var wpt = require('wpt');29var wptObj = new wpt();30wptObj.setResponseHeaders(function(err, data) {31 if(err) {32 console.log(err);33 } else {34 console.log(data);35 }36});37var wpt = require('wpt');38var wptObj = new wpt();39wptObj.getResponseHeaders(function(err, data) {40 if(err) {41 console.log(err);42 } else {43 console.log(data);44 }45});46var wpt = require('wpt');
Using AI Code Generation
1var wpt = require('wpt.js');2wpt.getResponseCookies(url, function(err, data) {3 console.log(data);4});5module.exports.getResponseCookies = function(url, callback) {6 var request = require('request');7 request.post({url: wptUrl, form: {url: url, k: wptKey, f: 'json'}}, function(err, response, body) {8 if (err) {9 callback(err);10 } else {11 var data = JSON.parse(body);12 callback(null, data);13 }14 });15};
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.getTestResults('160120_1G_1Y', function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data.response.cookies);8 }9});10{ '0': 11 { name: 'PHPSESSID',12 httponly: true },13 { name: 'wpt_session',14 httponly: true } }15var wpt = require('webpagetest');16var wpt = new WebPageTest('www.webpagetest.org');17wpt.getTestResults('160120_1G_1Y', function(err, data) {18 if (err) {19 console.log(err);20 } else {21 console.log(data.response.cookies[0]);22 }23});24{ name: 'PHPSESSID',25 httponly: true }26var wpt = require('webpagetest');27var wpt = new WebPageTest('www.webpagetest.org');28wpt.getTestResults('160120_1G_1Y', function(err, data) {29 if (err) {30 console.log(err);31 } else {32 console.log(data.response.cookies[0].value);33 }34});35var wpt = require('webpagetest');36var wpt = new WebPageTest('www.webpagetest.org');37wpt.getTestResults('160120_1G_1
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var testId = '140613_0K_1';4wpt.getResponseCookies(url, function(err, data) {5 if (err) {6 console.log('Error: ' + err);7 } else {8 console.log('Cookies: ' + JSON.stringify(data));9 }10});11Cookies: {"cookies":[{"name":"__utma","value":"
Using AI Code Generation
1var cookies = wpt.getResponseCookies();2for (var i = 0; i < cookies.length; i++) {3 console.log(cookies[i].name + "=" + cookies[i].value);4}5var cookies = wpt.getResponseCookies();6for (var i = 0; i < cookies.length; i++) {7 var cookie = cookies[i];8 var cookieString = cookie.name + "=" + cookie.value + "; domain=" + cookie.domain + "; path=" + cookie.path;9 if (cookie.expires) {10 cookieString += "; expires=" + cookie.expires;11 }12 if (cookie.httpOnly) {13 cookieString += "; HttpOnly";14 }15 if (cookie.secure) {16 cookieString += "; secure";17 }18 document.cookie = cookieString;19}20var cookies = wpt.getResponseCookies();21for (var i =
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!