Best JavaScript code snippet using mountebank
cli-find.js
Source:cli-find.js
1#!/usr/bin/env node2const Proxy = require('http-mitm-proxy');3const EventEmitter = require('events');4const program = require('commander');5const QRCode = require('qrcode');6const path = require('path');7const os = require('os');8const JSON5 = require('json5');9const fs = require('fs-extra');10// Disable debug messages from the proxy11try {12 require('debug').disable();13} catch(ex) {}14const ROOT = path.resolve(__dirname);15const pemFile = path.join(ROOT, 'certs', 'ca.pem');16let localIPs = [];17const ifaces = os.networkInterfaces();18Object.keys(ifaces).forEach(name => {19 ifaces[name].forEach(network => {20 if (network.family === 'IPv4' && !network.internal) localIPs.push(network.address);21 });22});23const proxy = Proxy();24const emitter = new EventEmitter();25program26 .name('tuya-lan find')27 .option('--ip <ip>', 'IP address to listen for requests')28 .option('-p, --port <port>', 'port the proxy should listen on', 8060)29 .option('--schema', 'include schema in the output')30 .parse(process.argv);31if (program.ip) {32 if (localIPs.includes(program.ip)) localIPs = [program.ip];33 else {34 console.log(`The requested IP, ${program.ip}, is not a valid external IPv4 address. The valid options are:\n\t${localIPs.join('\n\t')}`);35 process.exit();36 }37}38if (localIPs.length > 1) {39 console.log(`You have multiple network interfaces: ${localIPs.join(', ')}\nChoose one by passing it with the --ip parameter.\n\nExample: tuya-lan-find --ip ${localIPs[0]}`);40 process.exit();41}42const localIPPorts = localIPs.map(ip => `${ip}:${program.port}`);43const escapeUnicode = str => str.replace(/[\u00A0-\uffff]/gu, c => "\\u" + ("000" + c.charCodeAt().toString(16)).slice(-4));44proxy.onError(function(ctx, err) {45 switch (err.code) {46 case 'ERR_STREAM_DESTROYED':47 case 'ECONNRESET':48 return;49 case 'ECONNREFUSED':50 console.error('Failed to intercept secure communications. This could happen due to bad CA certificate.');51 return;52 case 'EACCES':53 console.error(`Permission was denied to use port ${program.port}.`);54 return;55 default:56 console.error('Error:', err.code, err);57 }58});59proxy.onRequest(function(ctx, callback) {60 if (ctx.clientToProxyRequest.method === 'GET' && ctx.clientToProxyRequest.url === '/cert' && localIPPorts.includes(ctx.clientToProxyRequest.headers.host)) {61 ctx.use(Proxy.gunzip);62 console.log('Intercepted certificate request');63 ctx.proxyToClientResponse.writeHeader(200, {64 'Accept-Ranges': 'bytes',65 'Cache-Control': 'public, max-age=0',66 'Content-Type': 'application/x-x509-ca-cert',67 'Content-Disposition': 'attachment; filename=cert.pem',68 'Content-Transfer-Encoding': 'binary',69 'Content-Length': fs.statSync(pemFile).size,70 'Connection': 'keep-alive',71 });72 //ctx.proxyToClientResponse.end(fs.readFileSync(path.join(ROOT, 'certs', 'ca.pem')));73 ctx.proxyToClientResponse.write(fs.readFileSync(pemFile));74 ctx.proxyToClientResponse.end();75 return;76 } else if (ctx.clientToProxyRequest.method === 'POST' && /tuya/.test(ctx.clientToProxyRequest.headers.host)) {77 ctx.use(Proxy.gunzip);78 ctx.onRequestData(function(ctx, chunk, callback) {79 return callback(null, chunk);80 });81 ctx.onRequestEnd(function(ctx, callback) {82 callback();83 });84 let chunks = [];85 ctx.onResponseData(function(ctx, chunk, callback) {86 chunks.push(chunk);87 return callback(null, chunk);88 });89 ctx.onResponseEnd(function(ctx, callback) {90 emitter.emit('tuya-config', Buffer.concat(chunks).toString());91 callback();92 });93 }94 return callback();95});96emitter.on('tuya-config', body => {97 if (body.indexOf('tuya.m.my.group.device.list') === -1) return;98 console.log('Intercepted config from Tuya');99 let data;100 const fail = (msg, err) => {101 console.error(msg, err);102 process.exit(1);103 };104 try {105 data = JSON.parse(body);106 } catch (ex) {107 return fail('There was a problem decoding config:', ex);108 }109 if (!Array.isArray(data.result)) return fail('Couldn\'t find a valid result-set.');110 let devices = [];111 data.result.some(data => {112 if (data && data.a === 'tuya.m.my.group.device.list') {113 devices = data.result;114 return true;115 }116 return false;117 });118 if (!Array.isArray(devices)) return fail('Couldn\'t find a good list of devices.');119 console.log(`\nFound ${devices.length} device${devices.length === 1 ? '' : 's'}:`);120 const foundDevices = devices.map(device => {121 return {122 name: device.name,123 id: device.devId,124 key: device.localKey,125 pid: device.productId126 }127 });128 if (program.schema) {129 let schemas = [];130 data.result.some(data => {131 if (data && data.a === 'tuya.m.device.ref.info.my.list') {132 schemas = data.result;133 return true;134 }135 return false;136 });137 if (Array.isArray(schemas)) {138 const defs = {};139 schemas.forEach(schema => {140 if (schema.id && schema.schemaInfo) {141 defs[schema.id] = {};142 if (schema.schemaInfo.schema) defs[schema.id].schema = escapeUnicode(schema.schemaInfo.schema);143 if (schema.schemaInfo.schemaExt && schema.schemaInfo.schemaExt !== '[]') defs[schema.id].extras = escapeUnicode(schema.schemaInfo.schemaExt);144 }145 });146 foundDevices.forEach(device => {147 if (defs[device.pid]) device.def = defs[device.pid];148 });149 } else console.log('Didn\'t find schema definitions. You will need to identify the data-points manually if this is a new device.');150 }151 foundDevices.forEach(device => {152 delete device.pid;153 });154 console.log(JSON5.stringify(foundDevices, '\n', 2));155 setTimeout(() => {156 process.exit(0);157 }, 5000);158});159proxy.listen({port: program.port, sslCaDir: ROOT}, err => {160 if (err) {161 console.error('Error starting proxy: ' + err);162 return setTimeout(() => {163 process.exit(0);164 }, 5000);165 }166 let {address, port} = proxy.httpServer.address();167 if (address === '::' || address === '0.0.0.0') address = localIPs[0];168 QRCode.toString(`http://${address}:${port}/cert`, {type: 'terminal'}, function(err, url) {169 console.log(url);170 console.log('\nFollow the instructions on https://github.com/AMoo-Miki/homebridge-tuya-lan/wiki/Setup-Instructions');171 console.log(`Proxy IP: ${address}`);172 console.log(`Proxy Port: ${port}\n\n`);173 })...
test-localAddress.js
Source:test-localAddress.js
1'use strict'2var request = require('../index')3 , tape = require('tape')4tape('bind to invalid address', function (t) {5 request.get({6 uri: 'http://www.google.com',7 localAddress: '1.2.3.4'8 }, function (err, res) {9 t.notEqual(err, null)10 t.equal(true, /bind EADDRNOTAVAIL/.test(err.message))11 t.equal(res, undefined)12 t.end()13 })14})15tape('bind to local address', function (t) {16 request.get({17 uri: 'http://www.google.com',18 localAddress: '127.0.0.1'19 }, function (err, res) {20 t.notEqual(err, null)21 t.equal(res, undefined)22 t.end()23 })24})25tape('bind to local address on redirect', function (t) {26 var os = require('os')27 var localInterfaces = os.networkInterfaces()28 var localIPS = []29 Object.keys(localInterfaces).forEach(function (ifname) {30 localInterfaces[ifname].forEach(function (iface) {31 if (iface.family !== 'IPv4' || iface.internal !== false) {32 // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses33 return34 }35 localIPS.push(iface.address)36 })37 })38 request.get({39 uri: 'http://google.com', //redirects to 'http://google.com'40 localAddress: localIPS[0]41 }, function (err, res) {42 t.equal(err, null)43 t.equal(res.request.localAddress, localIPS[0])44 t.end()45 })...
getIP.js
Source:getIP.js
1const { networkInterfaces } = require("os");2module.exports = {3 getLocalIP() {4 const nets = networkInterfaces();5 let localIPs = [];6 for (const name of Object.keys(nets)) {7 for (const net of nets[name]) {8 // Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses9 if (net.family === "IPv4" && !net.internal) {10 localIPs = [...localIPs, net.address];11 }12 }13 }14 const intIPs = localIPs.map(ip => {15 const noDots = ip.split(".").join("");16 return Number(noDots);17 });18 const smallestIndex = intIPs.findIndex(num => num === Math.min(...intIPs));19 const localIP = localIPs[smallestIndex];20 return localIP;21 },...
Using AI Code Generation
1var mb = require('mountebank');2var Q = require('q');3 {4 {5 {6 is: {7 headers: {8 },9 body: JSON.stringify({name: 'test'})10 }11 }12 }13 }14];15mb.create({port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*']})16 .then(function (instance) {17 console.log(instance);18 instance.createImposter(imposters[0]);19 })20 .done();21var mb = require('mountebank');22var Q = require('q');23 {24 {25 {26 is: {27 headers: {28 },29 body: JSON.stringify({name: 'test'})30 }31 }32 }33 }34];35mb.create({port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', localOnly: true})36 .then(function (instance) {37 console.log(instance);38 instance.createImposter(imposters[0]);39 })40 .done();
Using AI Code Generation
1const mb = require('mountebank');2const ips = mb.localIPs();3console.log(ips);4const mb = require('mountebank');5const ips = mb.localIPs();6console.log(ips);7const mb = require('mountebank');8const ips = mb.localIPs();9console.log(ips);10const mb = require('mountebank');11const ips = mb.localIPs();12console.log(ips);13const mb = require('mountebank');14const ips = mb.localIPs();15console.log(ips);16const mb = require('mountebank');17const ips = mb.localIPs();18console.log(ips);19const mb = require('mountebank');20const ips = mb.localIPs();21console.log(ips);22const mb = require('mountebank');23const ips = mb.localIPs();24console.log(ips);25const mb = require('mountebank');26const ips = mb.localIPs();27console.log(ips);28const mb = require('mountebank');29const ips = mb.localIPs();30console.log(ips);31const mb = require('mountebank');32const ips = mb.localIPs();33console.log(ips);34const mb = require('mountebank');35const ips = mb.localIPs();36console.log(ips);37const mb = require('mount
Using AI Code Generation
1var mb = require('mountebank');2mb.create({port:2525, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*']}, function (error, imposter) {3 if (error) {4 console.error('Error creating mountebank server: ' + error.message);5 return;6 }7 console.log('Mountebank server started on port ' + imposter.port);8});9var imposter = require('mountebank').createImposter({port: 2525, protocol: 'http', ipWhitelist: ['*']});10imposter.addStub({11 {12 is: {13 headers: {14 },15 }16 }17});18imposter.save(function (error) {19 if (error) {20 console.error('Error creating imposter: ' + error.message);21 return;22 }23 console.log('Imposter started on port ' + imposter.port);24});25var imposter = require('mountebank').createImposter({port: 2525, protocol: 'http'});26var stub = imposter.addStub({27 {28 is: {29 headers: {30 },31 }32 }33});34stub.save(function (error) {35 if (error) {36 console.error('Error creating stub: ' + error.message);37 return;38 }39 console.log('Imposter started on port ' + imposter.port);40});41var imposter = require('mountebank').createImposter({port: 2525, protocol: 'http'});42var stub = imposter.addStub({43 {44 is: {45 headers: {46 },47 }48 }49});50var predicate = stub.addPredicate({51 equals: {52 },
Using AI Code Generation
1var mb = require('mountebank');2mb.create({port:2525, pidfile: './mb.pid', logfile: './mb.log', protofile: './mb.proto'}, function (error, mb) {3 if (error) {4 console.log("Error creating mountebank server: " + error);5 } else {6 console.log("Mountebank server started");7 mb.localIPs(function (error, ips) {8 if (error) {9 console.log("Error getting local IPs: " + error);10 } else {11 console.log("Local IPs: " + ips);12 }13 });14 }15});
Using AI Code Generation
1var mb = require('mountebank');2var mbHelper = require('mountebank-helper');3var mbHelper = require('mountebank-helper');4 {5 {6 {7 is: {8 headers: {9 },10 }11 }12 }13 }14];15mb.create({ imposters: imposters }, function (error, imposter) {16 if (error) {17 console.error(error);18 }19 else {20 console.log('imposter created at: ' + imposter.url);21 console.log('imposter created at: ' + imposter.localIPs);22 if (error) {23 console.error(error);24 }25 else {26 console.log(response.body);27 }28 });29 }30});
Using AI Code Generation
1var localIPs = require('mountebank/src/util/localIps');2var ip = localIPs()[0];3var port = 2525;4var imposters = {5 {6 {7 'is': {8 }9 }10 }11};12var options = {13};14request(options, function (error, response, body) {15 if (!error && response.statusCode == 201) {16 console.log(body);17 }18});19var options = {20};21request(options, function (error, response, body) {22 if (!error && response.statusCode == 200) {23 console.log(body);24 }25});26var options = {27};28request(options, function (error, response, body) {29 if (!error && response.statusCode == 200) {30 console.log(body);31 }32});33var options = {34};35request(options, function (error, response, body) {36 if (!error && response.statusCode == 200) {37 console.log(body);38 }39});40var options = {41};42request(options, function (error, response, body) {43 if (!
Using AI Code Generation
1var mb = require('mountebank');2var Q = require('q');3var localIPs = mb.localIPs();4console.log('localIPs: ' + localIPs);5 {6 {7 {8 is: {9 }10 }11 }12 }13];14mb.start({ imposters: imposters }).then(function () {15 console.log('running');16 return Q.delay(1000);17}).then(function () {18 return mb.stop();19}).then(function () {20 console.log('stopped');21}).done();
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!!