How to use buildConnectReqHead method in Cypress

Best JavaScript code snippet using cypress

agent.js

Source:agent.js Github

copy

Full Screen

...17const debug = (0, debug_1.default)('cypress:network:agent');18const CRLF = '\r\n';19const statusCodeRe = /^HTTP\/1.[01] (\d*)/;20exports.clientCertificateStore = new client_certificates_1.ClientCertificateStore();21function buildConnectReqHead(hostname, port, proxy) {22 const connectReq = [`CONNECT ${hostname}:${port} HTTP/1.1`];23 connectReq.push(`Host: ${hostname}:${port}`);24 if (proxy.auth) {25 connectReq.push(`Proxy-Authorization: basic ${Buffer.from(proxy.auth).toString('base64')}`);26 }27 return connectReq.join(CRLF) + lodash_1.default.repeat(CRLF, 2);28}29exports.buildConnectReqHead = buildConnectReqHead;30const createProxySock = (opts, cb) => {31 if (opts.proxy.protocol !== 'https:' && opts.proxy.protocol !== 'http:') {32 return cb(new Error(`Unsupported proxy protocol: ${opts.proxy.protocol}`));33 }34 const isHttps = opts.proxy.protocol === 'https:';35 const port = opts.proxy.port || (isHttps ? 443 : 80);36 let connectOpts = {37 port: Number(port),38 host: opts.proxy.hostname,39 useTls: isHttps,40 };41 if (!opts.shouldRetry) {42 connectOpts.getDelayMsForRetry = () => undefined;43 }44 (0, connect_1.createRetryingSocket)(connectOpts, (err, sock, triggerRetry) => {45 if (err) {46 return cb(err);47 }48 cb(undefined, sock, triggerRetry);49 });50};51exports.createProxySock = createProxySock;52const isRequestHttps = (options) => {53 // WSS connections will not have an href, but you can tell protocol from the defaultAgent54 return lodash_1.default.get(options, '_defaultAgent.protocol') === 'https:' || (options.href || '').slice(0, 6) === 'https';55};56exports.isRequestHttps = isRequestHttps;57const isResponseStatusCode200 = (head) => {58 // read status code from proxy's response59 const matches = head.match(statusCodeRe);60 return lodash_1.default.get(matches, 1) === '200';61};62exports.isResponseStatusCode200 = isResponseStatusCode200;63const regenerateRequestHead = (req) => {64 delete req._header;65 req._implicitHeader();66 if (req.output && req.output.length > 0) {67 // the _header has already been queued to be written to the socket68 const first = req.output[0];69 const endOfHeaders = first.indexOf(lodash_1.default.repeat(CRLF, 2)) + 4;70 req.output[0] = req._header + first.substring(endOfHeaders);71 }72};73exports.regenerateRequestHead = regenerateRequestHead;74const getFirstWorkingFamily = ({ port, host }, familyCache, cb) => {75 // this is a workaround for localhost (and potentially others) having invalid76 // A records but valid AAAA records. here, we just cache the family of the first77 // returned A/AAAA record for a host that we can establish a connection to.78 // https://github.com/cypress-io/cypress/issues/11279 const isIP = net_1.default.isIP(host);80 if (isIP) {81 // isIP conveniently returns the family of the address82 return cb(isIP);83 }84 if (process.env.HTTP_PROXY) {85 // can't make direct connections through the proxy, this won't work86 return cb();87 }88 if (familyCache[host]) {89 return cb(familyCache[host]);90 }91 return (0, connect_1.getAddress)(port, host)92 .then((firstWorkingAddress) => {93 familyCache[host] = firstWorkingAddress.family;94 return cb(firstWorkingAddress.family);95 })96 .catch(() => {97 return cb();98 });99};100class CombinedAgent {101 constructor(httpOpts = {}, httpsOpts = {}) {102 this.familyCache = {};103 this.httpAgent = new HttpAgent(httpOpts);104 this.httpsAgent = new HttpsAgent(httpsOpts);105 }106 // called by Node.js whenever a new request is made internally107 addRequest(req, options, port, localAddress) {108 lodash_1.default.merge(req, http_utils_1.lenientOptions);109 // Legacy API: addRequest(req, host, port, localAddress)110 // https://github.com/nodejs/node/blob/cb68c04ce1bc4534b2d92bc7319c6ff6dda0180d/lib/_http_agent.js#L148-L155111 if (typeof options === 'string') {112 // @ts-ignore113 options = {114 host: options,115 port: port,116 localAddress,117 };118 }119 const isHttps = (0, exports.isRequestHttps)(options);120 if (!options.href) {121 // options.path can contain query parameters, which url.format will not-so-kindly urlencode for us...122 // so just append it to the resultant URL string123 options.href = url_1.default.format({124 protocol: isHttps ? 'https:' : 'http:',125 slashes: true,126 hostname: options.host,127 port: options.port,128 }) + options.path;129 if (!options.uri) {130 options.uri = url_1.default.parse(options.href);131 }132 }133 debug('addRequest called %o', Object.assign({ isHttps }, lodash_1.default.pick(options, 'href')));134 return getFirstWorkingFamily(options, this.familyCache, (family) => {135 options.family = family;136 debug('got family %o', lodash_1.default.pick(options, 'family', 'href'));137 if (isHttps) {138 lodash_1.default.assign(options, exports.clientCertificateStore.getClientCertificateAgentOptionsForUrl(options.uri));139 return this.httpsAgent.addRequest(req, options);140 }141 this.httpAgent.addRequest(req, options);142 });143 }144}145exports.CombinedAgent = CombinedAgent;146class HttpAgent extends http_1.default.Agent {147 constructor(opts = {}) {148 opts.keepAlive = true;149 super(opts);150 // we will need this if they wish to make http requests over an https proxy151 this.httpsAgent = new https_1.default.Agent({ keepAlive: true });152 }153 addRequest(req, options) {154 if (process.env.HTTP_PROXY) {155 const proxy = (0, proxy_from_env_1.getProxyForUrl)(options.href);156 if (proxy) {157 options.proxy = proxy;158 return this._addProxiedRequest(req, options);159 }160 }161 super.addRequest(req, options);162 }163 _addProxiedRequest(req, options) {164 debug(`Creating proxied request for ${options.href} through ${options.proxy}`);165 const proxy = url_1.default.parse(options.proxy);166 // set req.path to the full path so the proxy can resolve it167 // @ts-ignore: Cannot assign to 'path' because it is a constant or a read-only property.168 req.path = options.href;169 delete req._header; // so we can set headers again170 req.setHeader('host', `${options.host}:${options.port}`);171 if (proxy.auth) {172 req.setHeader('proxy-authorization', `basic ${Buffer.from(proxy.auth).toString('base64')}`);173 }174 // node has queued an HTTP message to be sent already, so we need to regenerate the175 // queued message with the new path and headers176 // https://github.com/TooTallNate/node-http-proxy-agent/blob/master/index.js#L93177 (0, exports.regenerateRequestHead)(req);178 options.port = Number(proxy.port || 80);179 options.host = proxy.hostname || 'localhost';180 delete options.path; // so the underlying net.connect doesn't default to IPC181 if (proxy.protocol === 'https:') {182 // gonna have to use the https module to reach the proxy, even though this is an http req183 req.agent = this.httpsAgent;184 return this.httpsAgent.addRequest(req, options);185 }186 super.addRequest(req, options);187 }188}189class HttpsAgent extends https_1.default.Agent {190 constructor(opts = {}) {191 opts.keepAlive = true;192 super(opts);193 }194 createConnection(options, cb) {195 if (process.env.HTTPS_PROXY) {196 const proxy = (0, proxy_from_env_1.getProxyForUrl)(options.href);197 if (proxy) {198 options.proxy = proxy;199 return this.createUpstreamProxyConnection(options, cb);200 }201 }202 // @ts-ignore203 cb(null, super.createConnection(options));204 }205 createUpstreamProxyConnection(options, cb) {206 // heavily inspired by207 // https://github.com/mknj/node-keepalive-proxy-agent/blob/master/index.js208 debug(`Creating proxied socket for ${options.href} through ${options.proxy}`);209 const proxy = url_1.default.parse(options.proxy);210 const port = options.uri.port || '443';211 const hostname = options.uri.hostname || 'localhost';212 (0, exports.createProxySock)({ proxy, shouldRetry: options.shouldRetry }, (originalErr, proxySocket, triggerRetry) => {213 if (originalErr) {214 const err = new Error(`A connection to the upstream proxy could not be established: ${originalErr.message}`);215 err.originalErr = originalErr;216 err.upstreamProxyConnect = true;217 return cb(err, undefined);218 }219 const onClose = () => {220 triggerRetry(new Error('ERR_EMPTY_RESPONSE: The upstream proxy closed the socket after connecting but before sending a response.'));221 };222 const onError = (err) => {223 triggerRetry(err);224 proxySocket.destroy();225 };226 let buffer = '';227 const onData = (data) => {228 debug(`Proxy socket for ${options.href} established`);229 buffer += data.toString();230 if (!lodash_1.default.includes(buffer, lodash_1.default.repeat(CRLF, 2))) {231 // haven't received end of headers yet, keep buffering232 proxySocket.once('data', onData);233 return;234 }235 // we've now gotten enough of a response not to retry236 // connecting to the proxy237 proxySocket.removeListener('error', onError);238 proxySocket.removeListener('close', onClose);239 if (!(0, exports.isResponseStatusCode200)(buffer)) {240 return cb(new Error(`Error establishing proxy connection. Response from server was: ${buffer}`), undefined);241 }242 if (options._agentKey) {243 // https.Agent will upgrade and reuse this socket now244 options.socket = proxySocket;245 // as of Node 12, a ServerName cannot be an IP address246 // https://github.com/cypress-io/cypress/issues/5729247 if (!net_1.default.isIP(hostname)) {248 options.servername = hostname;249 }250 return cb(undefined, super.createConnection(options, undefined));251 }252 cb(undefined, proxySocket);253 };254 proxySocket.once('close', onClose);255 proxySocket.once('error', onError);256 proxySocket.once('data', onData);257 const connectReq = buildConnectReqHead(hostname, port, proxy);258 proxySocket.setNoDelay(true);259 proxySocket.write(connectReq);260 });261 }262}263const agent = new CombinedAgent();...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.buildConnectReqHead().then((reqHead) => {2 cy.buildConnectReqHead().then((reqHead) => {3 cy.buildConnectReqHead().then((reqHead) => {4 cy.buildConnectReqHead().then((reqHead) => {5 cy.buildConnectReqHead().then((reqHead) => {6 cy.buildConnectReqHead().then((reqHead) => {7 cy.buildConnectReqHead().then((reqHead) => {8 cy.buildConnectReqHead().then((reqHead) => {9 cy.buildConnectReqHead().then((reqHead) => {10 cy.buildConnectReqHead().then((reqHead) => {11 cy.buildConnectReqHead().then((reqHead) => {12 cy.buildConnectReqHead().then((reqHead) => {13 cy.buildConnectReqHead().then((reqHead) => {14 cy.buildConnectReqHead().then((reqHead) => {15 cy.buildConnectReqHead().then((reqHead) => {16 cy.buildConnectReqHead().then((reqHead) => {17 cy.buildConnectReqHead().then((reqHead) => {18 cy.buildConnectReqHead().then((reqHead) => {19 cy.buildConnectReqHead().then((reqHead) => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const Cypress = require('./cypress');2const cypress = new Cypress();3cypress.buildConnectReqHead();4buildConnectReqHead() {5 const reqHead = new Buffer(16);6 reqHead.writeUInt16BE(0x0001, 0);7 reqHead.writeUInt16BE(0x0000, 2);8 reqHead.writeUInt16BE(0x0000, 4);9 reqHead.writeUInt16BE(0x0000, 6);10 reqHead.writeUInt16BE(0x0000, 8);11 reqHead.writeUInt16BE(0x0000, 10);12 reqHead.writeUInt16BE(0x0000, 12);13 reqHead.writeUInt16BE(0x0000, 14);14 return reqHead;15 }

Full Screen

Using AI Code Generation

copy

Full Screen

1const Cypress = require('./cypress.js');2let cypress = new Cypress();3let connectReqHead = cypress.buildConnectReqHead();4console.log(connectReqHead);5### 4. buildRequestHead()6const Cypress = require('./cypress.js');7let cypress = new Cypress();8let requestHead = cypress.buildRequestHead('www.google.com', 443, 'GET', '/search?q=hello');9console.log(requestHead);10### 5. buildResponseHead()11const Cypress = require('./cypress.js');12let cypress = new Cypress();13let responseHead = cypress.buildResponseHead(200, 'OK', 'text/html');14console.log(responseHead);15* The buildResponseHead() method takes 3 arguments: statusCode, statusMessage,

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress 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