Best Python code snippet using localstack_python
IP.mjs
Source:IP.mjs  
1/**2 * IP resources.3 *4 * @author picapi5 * @author n1474335 [n1474335@gmail.com]6 * @author Klaxon [klaxon@veyr.com]7 * @copyright Crown Copyright 20168 * @license Apache-2.09 */10import Utils from "../Utils.mjs";11import OperationError from "../errors/OperationError.mjs";12/**13 * Parses an IPv4 CIDR range (e.g. 192.168.0.0/24) and displays information about it.14 *15 * @param {RegExp} cidr16 * @param {boolean} includeNetworkInfo17 * @param {boolean} enumerateAddresses18 * @param {boolean} allowLargeList19 * @returns {string}20 */21export function ipv4CidrRange(cidr, includeNetworkInfo, enumerateAddresses, allowLargeList) {22    const network = strToIpv4(cidr[1]),23        cidrRange = parseInt(cidr[2], 10);24    let output = "";25    if (cidrRange < 0 || cidrRange > 31) {26        throw new OperationError("IPv4 CIDR must be less than 32");27    }28    const mask = ~(0xFFFFFFFF >>> cidrRange),29        ip1 = network & mask,30        ip2 = ip1 | ~mask;31    if (includeNetworkInfo) {32        output += "Network: " + ipv4ToStr(network) + "\n";33        output += "CIDR: " + cidrRange + "\n";34        output += "Mask: " + ipv4ToStr(mask) + "\n";35        output += "Range: " + ipv4ToStr(ip1) + " - " + ipv4ToStr(ip2) + "\n";36        output += "Total addresses in range: " + (((ip2 - ip1) >>> 0) + 1) + "\n\n";37    }38    if (enumerateAddresses) {39        if (cidrRange >= 16 || allowLargeList) {40            output += generateIpv4Range(ip1, ip2).join("\n");41        } else {42            output += _LARGE_RANGE_ERROR;43        }44    }45    return output;46}47/**48 * Parses an IPv6 CIDR range (e.g. ff00::/48) and displays information about it.49 *50 * @param {RegExp} cidr51 * @param {boolean} includeNetworkInfo52 * @returns {string}53 */54export function ipv6CidrRange(cidr, includeNetworkInfo) {55    let output = "";56    const network = strToIpv6(cidr[1]),57        cidrRange = parseInt(cidr[cidr.length-1], 10);58    if (cidrRange < 0 || cidrRange > 127) {59        throw new OperationError("IPv6 CIDR must be less than 128");60    }61    const ip1 = new Array(8),62        ip2 = new Array(8),63        total = new Array(128);64    const mask = genIpv6Mask(cidrRange);65    let totalDiff = "";66    for (let i = 0; i < 8; i++) {67        ip1[i] = network[i] & mask[i];68        ip2[i] = ip1[i] | (~mask[i] & 0x0000FFFF);69        totalDiff = (ip2[i] - ip1[i]).toString(2);70        if (totalDiff !== "0") {71            for (let n = 0; n < totalDiff.length; n++) {72                total[i*16 + 16-(totalDiff.length-n)] = totalDiff[n];73            }74        }75    }76    if (includeNetworkInfo) {77        output += "Network: " + ipv6ToStr(network) + "\n";78        output += "Shorthand: " + ipv6ToStr(network, true) + "\n";79        output += "CIDR: " + cidrRange + "\n";80        output += "Mask: " + ipv6ToStr(mask) + "\n";81        output += "Range: " + ipv6ToStr(ip1) + " - " + ipv6ToStr(ip2) + "\n";82        output += "Total addresses in range: " + (parseInt(total.join(""), 2) + 1) + "\n\n";83    }84    return output;85}86/**87 * Parses an IPv4 hyphenated range (e.g. 192.168.0.0 - 192.168.0.255) and displays information88 * about it.89 *90 * @param {RegExp} range91 * @param {boolean} includeNetworkInfo92 * @param {boolean} enumerateAddresses93 * @param {boolean} allowLargeList94 * @returns {string}95 */96export function ipv4HyphenatedRange(range, includeNetworkInfo, enumerateAddresses, allowLargeList) {97    const ip1 = strToIpv4(range[0].split("-")[0].trim()),98        ip2 = strToIpv4(range[0].split("-")[1].trim());99    let output = "";100    // Calculate mask101    let diff = ip1 ^ ip2,102        cidr = 32,103        mask = 0;104    while (diff !== 0) {105        diff >>= 1;106        cidr--;107        mask = (mask << 1) | 1;108    }109    mask = ~mask >>> 0;110    const network = ip1 & mask,111        subIp1 = network & mask,112        subIp2 = subIp1 | ~mask;113    if (includeNetworkInfo) {114        output += `Minimum subnet required to hold this range:115\tNetwork: ${ipv4ToStr(network)}116\tCIDR: ${cidr}117\tMask: ${ipv4ToStr(mask)}118\tSubnet range: ${ipv4ToStr(subIp1)} - ${ipv4ToStr(subIp2)}119\tTotal addresses in subnet: ${(((subIp2 - subIp1) >>> 0) + 1)}120Range: ${ipv4ToStr(ip1)} - ${ipv4ToStr(ip2)}121Total addresses in range: ${(((ip2 - ip1) >>> 0) + 1)}122`;123    }124    if (enumerateAddresses) {125        if (((ip2 - ip1) >>> 0) <= 65536 || allowLargeList) {126            output += generateIpv4Range(ip1, ip2).join("\n");127        } else {128            output += _LARGE_RANGE_ERROR;129        }130    }131    return output;132}133/**134 * Parses an IPv6 hyphenated range (e.g. ff00:: - ffff::) and displays information about it.135 *136 * @param {RegExp} range137 * @param {boolean} includeNetworkInfo138 * @returns {string}139 */140export function ipv6HyphenatedRange(range, includeNetworkInfo) {141    const ip1 = strToIpv6(range[0].split("-")[0].trim()),142        ip2 = strToIpv6(range[0].split("-")[1].trim()),143        total = new Array(128).fill();144    let output = "",145        t = "",146        i;147    for (i = 0; i < 8; i++) {148        t = (ip2[i] - ip1[i]).toString(2);149        if (t !== "0") {150            for (let n = 0; n < t.length; n++) {151                total[i*16 + 16-(t.length-n)] = t[n];152            }153        }154    }155    if (includeNetworkInfo) {156        output += "Range: " + ipv6ToStr(ip1) + " - " + ipv6ToStr(ip2) + "\n";157        output += "Shorthand range: " + ipv6ToStr(ip1, true) + " - " + ipv6ToStr(ip2, true) + "\n";158        output += "Total addresses in range: " + (parseInt(total.join(""), 2) + 1) + "\n\n";159    }160    return output;161}162/**163 * Parses a list of IPv4 addresses separated by a new line (\n) and displays information164 * about it.165 *166 * @param {RegExp} list167 * @param {boolean} includeNetworkInfo168 * @param {boolean} enumerateAddresses169 * @param {boolean} allowLargeList170 * @returns {string}171 */172export function ipv4ListedRange(match, includeNetworkInfo, enumerateAddresses, allowLargeList) {173    let ipv4List = match[0].split("\n");174    ipv4List = ipv4List.filter(Boolean);175    const ipv4CidrList = ipv4List.filter(function(a) {176        return a.includes("/");177    });178    for (let i = 0; i < ipv4CidrList.length; i++) {179        const network = strToIpv4(ipv4CidrList[i].split("/")[0]);180        const cidrRange = parseInt(ipv4CidrList[i].split("/")[1], 10);181        if (cidrRange < 0 || cidrRange > 31) {182            throw new OperationError("IPv4 CIDR must be less than 32");183        }184        const mask = ~(0xFFFFFFFF >>> cidrRange),185            cidrIp1 = network & mask,186            cidrIp2 = cidrIp1 | ~mask;187        ipv4List.splice(ipv4List.indexOf(ipv4CidrList[i]), 1);188        ipv4List.push(ipv4ToStr(cidrIp1), ipv4ToStr(cidrIp2));189    }190    ipv4List = ipv4List.sort(ipv4Compare);191    const ip1 = ipv4List[0];192    const ip2 = ipv4List[ipv4List.length - 1];193    const range = [ip1 + " - " + ip2];194    return ipv4HyphenatedRange(range, includeNetworkInfo, enumerateAddresses, allowLargeList);195}196/**197 * Parses a list of IPv6 addresses separated by a new line (\n) and displays information198 * about it.199 *200 * @param {RegExp} list201 * @param {boolean} includeNetworkInfo202 * @returns {string}203 */204export function ipv6ListedRange(match, includeNetworkInfo) {205    let ipv6List = match[0].split("\n");206    ipv6List = ipv6List.filter(function(str) {207        return str.trim();208    });209    for (let i =0; i < ipv6List.length; i++) {210        ipv6List[i] = ipv6List[i].trim();211    }212    const ipv6CidrList = ipv6List.filter(function(a) {213        return a.includes("/");214    });215    for (let i = 0; i < ipv6CidrList.length; i++) {216        const network = strToIpv6(ipv6CidrList[i].split("/")[0]);217        const cidrRange = parseInt(ipv6CidrList[i].split("/")[1], 10);218        if (cidrRange < 0 || cidrRange > 127) {219            throw new OperationError("IPv6 CIDR must be less than 128");220        }221        const cidrIp1 = new Array(8),222            cidrIp2 = new Array(8);223        const mask = genIpv6Mask(cidrRange);224        for (let j = 0; j < 8; j++) {225            cidrIp1[j] = network[j] & mask[j];226            cidrIp2[j] = cidrIp1[j] | (~mask[j] & 0x0000FFFF);227        }228        ipv6List.splice(ipv6List.indexOf(ipv6CidrList[i]), 1);229        ipv6List.push(ipv6ToStr(cidrIp1), ipv6ToStr(cidrIp2));230    }231    ipv6List = ipv6List.sort(ipv6Compare);232    const ip1 = ipv6List[0];233    const ip2 = ipv6List[ipv6List.length - 1];234    const range = [ip1 + " - " + ip2];235    return ipv6HyphenatedRange(range, includeNetworkInfo);236}237/**238 * Converts an IPv4 address from string format to numerical format.239 *240 * @param {string} ipStr241 * @returns {number}242 *243 * @example244 * // returns 168427520245 * strToIpv4("10.10.0.0");246 */247export function strToIpv4(ipStr) {248    const blocks = ipStr.split("."),249        numBlocks = parseBlocks(blocks);250    let result = 0;251    result += numBlocks[0] << 24;252    result += numBlocks[1] << 16;253    result += numBlocks[2] << 8;254    result += numBlocks[3];255    return result;256    /**257     * Converts a list of 4 numeric strings in the range 0-255 to a list of numbers.258     */259    function parseBlocks(blocks) {260        if (blocks.length !== 4)261            throw new OperationError("More than 4 blocks.");262        const numBlocks = [];263        for (let i = 0; i < 4; i++) {264            numBlocks[i] = parseInt(blocks[i], 10);265            if (numBlocks[i] < 0 || numBlocks[i] > 255)266                throw new OperationError("Block out of range.");267        }268        return numBlocks;269    }270}271/**272 * Converts an IPv4 address from numerical format to string format.273 *274 * @param {number} ipInt275 * @returns {string}276 *277 * @example278 * // returns "10.10.0.0"279 * ipv4ToStr(168427520);280 */281export function ipv4ToStr(ipInt) {282    const blockA = (ipInt >> 24) & 255,283        blockB = (ipInt >> 16) & 255,284        blockC = (ipInt >> 8) & 255,285        blockD = ipInt & 255;286    return blockA + "." + blockB + "." + blockC + "." + blockD;287}288/**289 * Converts an IPv6 address from string format to numerical array format.290 *291 * @param {string} ipStr292 * @returns {number[]}293 *294 * @example295 * // returns [65280, 0, 0, 0, 0, 0, 4369, 8738]296 * strToIpv6("ff00::1111:2222");297 */298export function strToIpv6(ipStr) {299    let j = 0;300    const blocks = ipStr.split(":"),301        numBlocks = parseBlocks(blocks),302        ipv6 = new Array(8);303    for (let i = 0; i < 8; i++) {304        if (isNaN(numBlocks[j])) {305            ipv6[i] = 0;306            if (i === (8-numBlocks.slice(j).length)) j++;307        } else {308            ipv6[i] = numBlocks[j];309            j++;310        }311    }312    return ipv6;313    /**314     * Converts a list of 3-8 numeric hex strings in the range 0-65535 to a list of numbers.315     */316    function parseBlocks(blocks) {317        if (blocks.length < 3 || blocks.length > 8)318            throw new OperationError("Badly formatted IPv6 address.");319        const numBlocks = [];320        for (let i = 0; i < blocks.length; i++) {321            numBlocks[i] = parseInt(blocks[i], 16);322            if (numBlocks[i] < 0 || numBlocks[i] > 65535)323                throw new OperationError("Block out of range.");324        }325        return numBlocks;326    }327}328/**329 * Converts an IPv6 address from numerical array format to string format.330 *331 * @param {number[]} ipv6332 * @param {boolean} compact - Whether or not to return the address in shorthand or not333 * @returns {string}334 *335 * @example336 * // returns "ff00::1111:2222"337 * ipv6ToStr([65280, 0, 0, 0, 0, 0, 4369, 8738], true);338 *339 * // returns "ff00:0000:0000:0000:0000:0000:1111:2222"340 * ipv6ToStr([65280, 0, 0, 0, 0, 0, 4369, 8738], false);341 */342export function ipv6ToStr(ipv6, compact) {343    let output = "",344        i = 0;345    if (compact) {346        let start = -1,347            end = -1,348            s = 0,349            e = -1;350        for (i = 0; i < 8; i++) {351            if (ipv6[i] === 0 && e === (i-1)) {352                e = i;353            } else if (ipv6[i] === 0) {354                s = i; e = i;355            }356            if (e >= 0 && (e-s) > (end - start)) {357                start = s;358                end = e;359            }360        }361        for (i = 0; i < 8; i++) {362            if (i !== start) {363                output += Utils.hex(ipv6[i], 1) + ":";364            } else {365                output += ":";366                i = end;367                if (end === 7) output += ":";368            }369        }370        if (output[0] === ":")371            output = ":" + output;372    } else {373        for (i = 0; i < 8; i++) {374            output += Utils.hex(ipv6[i], 4) + ":";375        }376    }377    return output.slice(0, output.length-1);378}379/**380 * Generates a list of IPv4 addresses in string format between two given numerical values.381 *382 * @param {number} ip383 * @param {number} endIp384 * @returns {string[]}385 *386 * @example387 * // returns ["0.0.0.1", "0.0.0.2", "0.0.0.3"]388 * IP.generateIpv4Range(1, 3);389 */390export function generateIpv4Range(ip, endIp) {391    const range = [];392    if (endIp >= ip) {393        for (; ip <= endIp; ip++) {394            range.push(ipv4ToStr(ip));395        }396    } else {397        range[0] = "Second IP address smaller than first.";398    }399    return range;400}401/**402 * Generates an IPv6 subnet mask given a CIDR value.403 *404 * @param {number} cidr405 * @returns {number[]}406 */407export function genIpv6Mask(cidr) {408    const mask = new Array(8);409    let shift;410    for (let i = 0; i < 8; i++) {411        if (cidr > ((i+1)*16)) {412            mask[i] = 0x0000FFFF;413        } else {414            shift = cidr-(i*16);415            if (shift < 0) shift = 0;416            mask[i] = ~((0x0000FFFF >>> shift) | 0xFFFF0000);417        }418    }419    return mask;420}421/**422 * Comparison operation for sorting of IPv4 addresses.423 *424 * @param {string} a425 * @param {string} b426 * @returns {number}427 */428export function ipv4Compare(a, b) {429    return strToIpv4(a) - strToIpv4(b);430}431/**432 * Comparison operation for sorting of IPv6 addresses.433 *434 * @param {string} a435 * @param {string} b436 * @returns {number}437 */438export function ipv6Compare(a, b) {439    const a_ = strToIpv6(a),440        b_ = strToIpv6(b);441    for (let i = 0; i < a_.length; i++) {442        if (a_[i] !== b_[i]) {443            return a_[i] - b_[i];444        }445    }446    return 0;447}448const _LARGE_RANGE_ERROR = "The specified range contains more than 65,536 addresses. Running this query could crash your browser. If you want to run it, select the \"Allow large queries\" option. You are advised to turn off \"Auto Bake\" whilst editing large ranges.";449/**450 * A regular expression that matches an IPv4 address451 */452export const IPV4_REGEX = /^\s*((?:\d{1,3}\.){3}\d{1,3})\s*$/;453/**454 * A regular expression that matches an IPv6 address455 */456export const IPV6_REGEX = /^\s*(((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\4)::|:\b|(?![\dA-F])))|(?!\3\4)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4}))\s*$/i;457/**458 * Lookup table for Internet Protocols.459 * Taken from https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml460 */461export const protocolLookup = {462    0: {keyword: "HOPOPT", protocol: "IPv6 Hop-by-Hop Option"},463    1: {keyword: "ICMP", protocol: "Internet Control Message"},464    2: {keyword: "IGMP", protocol: "Internet Group Management"},465    3: {keyword: "GGP", protocol: "Gateway-to-Gateway"},466    4: {keyword: "IPv4", protocol: "IPv4 encapsulation"},467    5: {keyword: "ST", protocol: "Stream"},468    6: {keyword: "TCP", protocol: "Transmission Control"},469    7: {keyword: "CBT", protocol: "CBT"},470    8: {keyword: "EGP", protocol: "Exterior Gateway Protocol"},471    9: {keyword: "IGP", protocol: "any private interior gateway (used by Cisco for their IGRP)"},472    10: {keyword: "BBN-RCC-MON", protocol: "BBN RCC Monitoring"},473    11: {keyword: "NVP-II", protocol: "Network Voice Protocol"},474    12: {keyword: "PUP", protocol: "PUP"},475    13: {keyword: "ARGUS (deprecated)", protocol: "ARGUS"},476    14: {keyword: "EMCON", protocol: "EMCON"},477    15: {keyword: "XNET", protocol: "Cross Net Debugger"},478    16: {keyword: "CHAOS", protocol: "Chaos"},479    17: {keyword: "UDP", protocol: "User Datagram"},480    18: {keyword: "MUX", protocol: "Multiplexing"},481    19: {keyword: "DCN-MEAS", protocol: "DCN Measurement Subsystems"},482    20: {keyword: "HMP", protocol: "Host Monitoring"},483    21: {keyword: "PRM", protocol: "Packet Radio Measurement"},484    22: {keyword: "XNS-IDP", protocol: "XEROX NS IDP"},485    23: {keyword: "TRUNK-1", protocol: "Trunk-1"},486    24: {keyword: "TRUNK-2", protocol: "Trunk-2"},487    25: {keyword: "LEAF-1", protocol: "Leaf-1"},488    26: {keyword: "LEAF-2", protocol: "Leaf-2"},489    27: {keyword: "RDP", protocol: "Reliable Data Protocol"},490    28: {keyword: "IRTP", protocol: "Internet Reliable Transaction"},491    29: {keyword: "ISO-TP4", protocol: "ISO Transport Protocol Class 4"},492    30: {keyword: "NETBLT", protocol: "Bulk Data Transfer Protocol"},493    31: {keyword: "MFE-NSP", protocol: "MFE Network Services Protocol"},494    32: {keyword: "MERIT-INP", protocol: "MERIT Internodal Protocol"},495    33: {keyword: "DCCP", protocol: "Datagram Congestion Control Protocol"},496    34: {keyword: "3PC", protocol: "Third Party Connect Protocol"},497    35: {keyword: "IDPR", protocol: "Inter-Domain Policy Routing Protocol"},498    36: {keyword: "XTP", protocol: "XTP"},499    37: {keyword: "DDP", protocol: "Datagram Delivery Protocol"},500    38: {keyword: "IDPR-CMTP", protocol: "IDPR Control Message Transport Proto"},501    39: {keyword: "TP++", protocol: "TP++ Transport Protocol"},502    40: {keyword: "IL", protocol: "IL Transport Protocol"},503    41: {keyword: "IPv6", protocol: "IPv6 encapsulation"},504    42: {keyword: "SDRP", protocol: "Source Demand Routing Protocol"},505    43: {keyword: "IPv6-Route", protocol: "Routing Header for IPv6"},506    44: {keyword: "IPv6-Frag", protocol: "Fragment Header for IPv6"},507    45: {keyword: "IDRP", protocol: "Inter-Domain Routing Protocol"},508    46: {keyword: "RSVP", protocol: "Reservation Protocol"},509    47: {keyword: "GRE", protocol: "Generic Routing Encapsulation"},510    48: {keyword: "DSR", protocol: "Dynamic Source Routing Protocol"},511    49: {keyword: "BNA", protocol: "BNA"},512    50: {keyword: "ESP", protocol: "Encap Security Payload"},513    51: {keyword: "AH", protocol: "Authentication Header"},514    52: {keyword: "I-NLSP", protocol: "Integrated Net Layer Security  TUBA"},515    53: {keyword: "SWIPE (deprecated)", protocol: "IP with Encryption"},516    54: {keyword: "NARP", protocol: "NBMA Address Resolution Protocol"},517    55: {keyword: "MOBILE", protocol: "IP Mobility"},518    56: {keyword: "TLSP", protocol: "Transport Layer Security Protocol using Kryptonet key management"},519    57: {keyword: "SKIP", protocol: "SKIP"},520    58: {keyword: "IPv6-ICMP", protocol: "ICMP for IPv6"},521    59: {keyword: "IPv6-NoNxt", protocol: "No Next Header for IPv6"},522    60: {keyword: "IPv6-Opts", protocol: "Destination Options for IPv6"},523    61: {keyword: "", protocol: "any host internal protocol"},524    62: {keyword: "CFTP", protocol: "CFTP"},525    63: {keyword: "", protocol: "any local network"},526    64: {keyword: "SAT-EXPAK", protocol: "SATNET and Backroom EXPAK"},527    65: {keyword: "KRYPTOLAN", protocol: "Kryptolan"},528    66: {keyword: "RVD", protocol: "MIT Remote Virtual Disk Protocol"},529    67: {keyword: "IPPC", protocol: "Internet Pluribus Packet Core"},530    68: {keyword: "", protocol: "any distributed file system"},531    69: {keyword: "SAT-MON", protocol: "SATNET Monitoring"},532    70: {keyword: "VISA", protocol: "VISA Protocol"},533    71: {keyword: "IPCV", protocol: "Internet Packet Core Utility"},534    72: {keyword: "CPNX", protocol: "Computer Protocol Network Executive"},535    73: {keyword: "CPHB", protocol: "Computer Protocol Heart Beat"},536    74: {keyword: "WSN", protocol: "Wang Span Network"},537    75: {keyword: "PVP", protocol: "Packet Video Protocol"},538    76: {keyword: "BR-SAT-MON", protocol: "Backroom SATNET Monitoring"},539    77: {keyword: "SUN-ND", protocol: "SUN ND PROTOCOL-Temporary"},540    78: {keyword: "WB-MON", protocol: "WIDEBAND Monitoring"},541    79: {keyword: "WB-EXPAK", protocol: "WIDEBAND EXPAK"},542    80: {keyword: "ISO-IP", protocol: "ISO Internet Protocol"},543    81: {keyword: "VMTP", protocol: "VMTP"},544    82: {keyword: "SECURE-VMTP", protocol: "SECURE-VMTP"},545    83: {keyword: "VINES", protocol: "VINES"},546    84: {keyword: "TTP", protocol: "Transaction Transport Protocol"},547    85: {keyword: "NSFNET-IGP", protocol: "NSFNET-IGP"},548    86: {keyword: "DGP", protocol: "Dissimilar Gateway Protocol"},549    87: {keyword: "TCF", protocol: "TCF"},550    88: {keyword: "EIGRP", protocol: "EIGRP"},551    89: {keyword: "OSPFIGP", protocol: "OSPFIGP"},552    90: {keyword: "Sprite-RPC", protocol: "Sprite RPC Protocol"},553    91: {keyword: "LARP", protocol: "Locus Address Resolution Protocol"},554    92: {keyword: "MTP", protocol: "Multicast Transport Protocol"},555    93: {keyword: "AX.25", protocol: "AX.25 Frames"},556    94: {keyword: "IPIP", protocol: "IP-within-IP Encapsulation Protocol"},557    95: {keyword: "MICP (deprecated)", protocol: "Mobile Internetworking Control Pro."},558    96: {keyword: "SCC-SP", protocol: "Semaphore Communications Sec. Pro."},559    97: {keyword: "ETHERIP", protocol: "Ethernet-within-IP Encapsulation"},560    98: {keyword: "ENCAP", protocol: "Encapsulation Header"},561    99: {keyword: "", protocol: "any private encryption scheme"},562    100: {keyword: "GMTP", protocol: "GMTP"},563    101: {keyword: "IFMP", protocol: "Ipsilon Flow Management Protocol"},564    102: {keyword: "PNNI", protocol: "PNNI over IP"},565    103: {keyword: "PIM", protocol: "Protocol Independent Multicast"},566    104: {keyword: "ARIS", protocol: "ARIS"},567    105: {keyword: "SCPS", protocol: "SCPS"},568    106: {keyword: "QNX", protocol: "QNX"},569    107: {keyword: "A/N", protocol: "Active Networks"},570    108: {keyword: "IPComp", protocol: "IP Payload Compression Protocol"},571    109: {keyword: "SNP", protocol: "Sitara Networks Protocol"},572    110: {keyword: "Compaq-Peer", protocol: "Compaq Peer Protocol"},573    111: {keyword: "IPX-in-IP", protocol: "IPX in IP"},574    112: {keyword: "VRRP", protocol: "Virtual Router Redundancy Protocol"},575    113: {keyword: "PGM", protocol: "PGM Reliable Transport Protocol"},576    114: {keyword: "", protocol: "any 0-hop protocol"},577    115: {keyword: "L2TP", protocol: "Layer Two Tunneling Protocol"},578    116: {keyword: "DDX", protocol: "D-II Data Exchange (DDX)"},579    117: {keyword: "IATP", protocol: "Interactive Agent Transfer Protocol"},580    118: {keyword: "STP", protocol: "Schedule Transfer Protocol"},581    119: {keyword: "SRP", protocol: "SpectraLink Radio Protocol"},582    120: {keyword: "UTI", protocol: "UTI"},583    121: {keyword: "SMP", protocol: "Simple Message Protocol"},584    122: {keyword: "SM (deprecated)", protocol: "Simple Multicast Protocol"},585    123: {keyword: "PTP", protocol: "Performance Transparency Protocol"},586    124: {keyword: "ISIS over IPv4", protocol: ""},587    125: {keyword: "FIRE", protocol: ""},588    126: {keyword: "CRTP", protocol: "Combat Radio Transport Protocol"},589    127: {keyword: "CRUDP", protocol: "Combat Radio User Datagram"},590    128: {keyword: "SSCOPMCE", protocol: ""},591    129: {keyword: "IPLT", protocol: ""},592    130: {keyword: "SPS", protocol: "Secure Packet Shield"},593    131: {keyword: "PIPE", protocol: "Private IP Encapsulation within IP"},594    132: {keyword: "SCTP", protocol: "Stream Control Transmission Protocol"},595    133: {keyword: "FC", protocol: "Fibre Channel"},596    134: {keyword: "RSVP-E2E-IGNORE", protocol: ""},597    135: {keyword: "Mobility Header", protocol: ""},598    136: {keyword: "UDPLite", protocol: ""},599    137: {keyword: "MPLS-in-IP", protocol: ""},600    138: {keyword: "manet", protocol: "MANET Protocols"},601    139: {keyword: "HIP", protocol: "Host Identity Protocol"},602    140: {keyword: "Shim6", protocol: "Shim6 Protocol"},603    141: {keyword: "WESP", protocol: "Wrapped Encapsulating Security Payload"},604    142: {keyword: "ROHC", protocol: "Robust Header Compression"},605    253: {keyword: "", protocol: "Use for experimentation and testing"},606    254: {keyword: "", protocol: "Use for experimentation and testing"},607    255: {keyword: "Reserved", protocol: ""}...command-line-api.js
Source:command-line-api.js  
1// Copyright 2017 the V8 project authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4let {session, contextGroup, Protocol} = InspectorTest.start('Checks command line API.');5InspectorTest.runAsyncTestSuite([6  async function testKeys() {7    InspectorTest.logMessage(await Protocol.Runtime.evaluate({8      expression: 'keys', includeCommandLineAPI: true}));9    InspectorTest.logMessage(await Protocol.Runtime.evaluate({10      expression: 'keys({a : 1})', includeCommandLineAPI: true, returnByValue: true}));11    Protocol.Runtime.evaluate({expression: 'this.keys = keys', includeCommandLineAPI: true});12    InspectorTest.logMessage(await Protocol.Runtime.evaluate({13      expression: 'this.keys({a : 1})', returnByValue: true}));14  },15  async function testInspect() {16    InspectorTest.log(await Protocol.Runtime.evaluate({expression: 'inspect', includeCommandLineAPI: true}));17    await Protocol.Runtime.enable();18    Protocol.Runtime.onInspectRequested(InspectorTest.logMessage);19    await Protocol.Runtime.evaluate({expression: 'inspect({})', includeCommandLineAPI: true});20    await Protocol.Runtime.evaluate({expression: 'inspect(239)', includeCommandLineAPI: true});21    await Protocol.Runtime.evaluate({expression: 'inspect(-0)', includeCommandLineAPI: true});22    await Protocol.Runtime.evaluate({expression: 'copy(\'hello\')', includeCommandLineAPI: true});23    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: '$0', includeCommandLineAPI: true}));24    Protocol.Runtime.evaluate({expression: 'this.inspect = inspect', includeCommandLineAPI: true});25    await Protocol.Runtime.evaluate({expression: 'this.inspect({})'});26    Protocol.Runtime.onInspectRequested(null);27    await Protocol.Runtime.disable();28  },29  async function testQueryObjects() {30    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: 'queryObjects', includeCommandLineAPI: true}));31    await Protocol.Runtime.enable();32    let {result:{result:{objectId}}} = await Protocol.Runtime.evaluate({expression: 'Promise.prototype'});33    Protocol.Runtime.evaluate({expression: 'queryObjects(Promise)', includeCommandLineAPI: true});34    let request = await Protocol.Runtime.onceInspectRequested();35    InspectorTest.logMessage(request);36    InspectorTest.logMessage('Is Promise.prototype: ' + await isEqual(objectId, request.params.object.objectId));37    Protocol.Runtime.evaluate({expression: 'queryObjects(Promise.prototype)', includeCommandLineAPI: true});38    request = await Protocol.Runtime.onceInspectRequested();39    InspectorTest.logMessage(request);40    InspectorTest.logMessage('Is Promise.prototype: ' + await isEqual(objectId, request.params.object.objectId));41    ({result:{result:{objectId}}} = await Protocol.Runtime.evaluate({expression:'p = {a:1}'}));42    Protocol.Runtime.evaluate({expression: 'queryObjects(p)', includeCommandLineAPI: true});43    request = await Protocol.Runtime.onceInspectRequested();44    InspectorTest.logMessage(request);45    InspectorTest.logMessage('Is p: ' + await isEqual(objectId, request.params.object.objectId));46    Protocol.Runtime.evaluate({expression: 'queryObjects(1)', includeCommandLineAPI: true});47    InspectorTest.logMessage(await Protocol.Runtime.onceInspectRequested());48    await Protocol.Runtime.disable();49  },50  async function testEvaluationResult() {51    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: '$_', includeCommandLineAPI: true}));52    await Protocol.Runtime.evaluate({expression: '42', objectGroup: 'console', includeCommandLineAPI: true});53    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: '$_', includeCommandLineAPI: true}));54    await Protocol.Runtime.evaluate({expression: '239', includeCommandLineAPI: true});55    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: '$_', includeCommandLineAPI: true}));56    await Protocol.Runtime.evaluate({expression: '-0', objectGroup: 'console', includeCommandLineAPI: true});57    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: '$_', includeCommandLineAPI: true}));58    await Protocol.Runtime.evaluate({expression: '({})', objectGroup: 'console', includeCommandLineAPI: true});59    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: '$_', includeCommandLineAPI: true, returnByValue: true}));60  },61  async function testDebug() {62    session.setupScriptMap();63    await Protocol.Debugger.enable();64    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: 'debug', includeCommandLineAPI: true}));65    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: 'undebug', includeCommandLineAPI: true}));66    await Protocol.Runtime.evaluate({expression: 'function foo() {}'});67    await Protocol.Runtime.evaluate({expression: 'debug(foo)', includeCommandLineAPI: true});68    Protocol.Runtime.evaluate({ expression: 'foo()'});69    let message = await Protocol.Debugger.oncePaused();70    session.logCallFrames(message.params.callFrames);71    InspectorTest.logMessage(message.params.hitBreakpoints);72    InspectorTest.logMessage(message.params.reason);73    await Protocol.Debugger.resume();74    await Protocol.Runtime.evaluate({expression: 'undebug(foo)', includeCommandLineAPI: true});75    await Protocol.Runtime.evaluate({ expression: 'foo()'});76    Protocol.Runtime.evaluate({77      expression: 'this.debug = debug; this.undebug = undebug;', includeCommandLineAPI: true});78    await Protocol.Runtime.evaluate({expression: 'this.debug(foo)'});79    Protocol.Runtime.evaluate({ expression: 'foo()'});80    message = await Protocol.Debugger.oncePaused();81    session.logCallFrames(message.params.callFrames);82    InspectorTest.logMessage(message.params.hitBreakpoints);83    InspectorTest.logMessage(message.params.reason);84    await Protocol.Debugger.resume();85    await Protocol.Runtime.evaluate({expression: 'this.undebug(foo)'});86    await Protocol.Runtime.evaluate({expression: 'foo()'});87    // Test builtin.88    await Protocol.Runtime.evaluate({expression: 'function toUpper(x) { return x.toUpperCase() }'});89    await Protocol.Runtime.evaluate({expression: 'debug(String.prototype.toUpperCase)', includeCommandLineAPI: true});90    Protocol.Runtime.evaluate({ expression: 'toUpper("first call")'});91    message = await Protocol.Debugger.oncePaused();92    session.logCallFrames(message.params.callFrames);93    InspectorTest.logMessage(message.params.hitBreakpoints);94    InspectorTest.logMessage(message.params.reason);95    await Protocol.Debugger.resume();96    await Protocol.Runtime.evaluate({expression: 'undebug(String.prototype.toUpperCase)', includeCommandLineAPI: true});97    await Protocol.Runtime.evaluate({ expression: 'toUpper("second call")'});98    // Test API callback.99    await Protocol.Runtime.evaluate({expression: 'function callSetTimeout() { setTimeout(function(){}, 0) }'});100    await Protocol.Runtime.evaluate({expression: 'debug(setTimeout)', includeCommandLineAPI: true});101    Protocol.Runtime.evaluate({ expression: 'callSetTimeout()'});102    message = await Protocol.Debugger.oncePaused();103    session.logCallFrames(message.params.callFrames);104    InspectorTest.logMessage(message.params.hitBreakpoints);105    InspectorTest.logMessage(message.params.reason);106    let breakpointId = message.params.hitBreakpoints[0];107    await Protocol.Debugger.resume();108    await Protocol.Runtime.evaluate({expression: 'undebug(setTimeout)', includeCommandLineAPI: true});109    await Protocol.Runtime.evaluate({ expression: 'callSetTimeout()'});110    // Test remove break via protocol.111    await Protocol.Runtime.evaluate({expression: 'function callSetTimeout() { setTimeout(function(){}, 0) }'});112    await Protocol.Runtime.evaluate({expression: 'debug(setTimeout)', includeCommandLineAPI: true});113    Protocol.Runtime.evaluate({ expression: 'callSetTimeout()'});114    message = await Protocol.Debugger.oncePaused();115    session.logCallFrames(message.params.callFrames);116    InspectorTest.logMessage(message.params.hitBreakpoints);117    InspectorTest.logMessage(message.params.reason);118    await Protocol.Debugger.resume();119    await Protocol.Debugger.removeBreakpoint({breakpointId});120    await Protocol.Runtime.evaluate({ expression: 'callSetTimeout()'});121    // Test condition.122    await Protocol.Runtime.evaluate({expression: 'function fromCharCode(...args) { String.fromCharCode(...args) }'});123    await Protocol.Runtime.evaluate({expression: 'debug(String.fromCharCode, "arguments.length == 3")'});124    Protocol.Runtime.evaluate({ expression: 'fromCharCode("1", "2", "3")'});125    message = await Protocol.Debugger.oncePaused();126    session.logCallFrames(message.params.callFrames);127    InspectorTest.logMessage(message.params.hitBreakpoints);128    InspectorTest.logMessage(message.params.reason);129    await Protocol.Runtime.evaluate({expression: 'undebug(String.fromCharCode)'});130    await Protocol.Runtime.evaluate({ expression: 'fromCharCode()'});131    await Protocol.Debugger.disable();132  },133  async function testMonitor() {134    await Protocol.Debugger.enable();135    await Protocol.Runtime.enable();136    Protocol.Runtime.onConsoleAPICalled(message => InspectorTest.log(message.params.args[0].value));137    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: 'monitor', includeCommandLineAPI: true}));138    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: 'unmonitor', includeCommandLineAPI: true}));139    await Protocol.Runtime.evaluate({expression: 'function foo() {}'});140    await Protocol.Runtime.evaluate({expression: 'monitor(foo)', includeCommandLineAPI: true});141    Protocol.Runtime.evaluate({ expression: 'foo(); console.log(\'after first call\')'});142    await Protocol.Runtime.evaluate({expression: 'unmonitor(foo)', includeCommandLineAPI: true});143    await Protocol.Runtime.evaluate({ expression: 'foo()'});144    Protocol.Runtime.evaluate({145      expression: 'console.log(\'store functions..\'); this.monitor = monitor; this.unmonitor = unmonitor;', includeCommandLineAPI: true});146    await Protocol.Runtime.evaluate({expression: 'this.monitor(foo)'});147    Protocol.Runtime.evaluate({ expression: 'foo(); console.log(\'after first call\')'});148    await Protocol.Runtime.evaluate({expression: 'this.unmonitor(foo)'});149    await Protocol.Runtime.evaluate({ expression: 'foo()'});150    // Test builtin.151    await Protocol.Runtime.evaluate({expression: 'function fromCharCode(...args) { String.fromCharCode(...args) }'});152    await Protocol.Runtime.evaluate({expression: 'monitor(String.fromCharCode)'});153    Protocol.Runtime.evaluate({ expression: 'fromCharCode("1", "2", "3")'});154    await Protocol.Runtime.evaluate({expression: 'unmonitor(String.fromCharCode)'});155    await Protocol.Runtime.evaluate({ expression: 'fromCharCode()'});156    Protocol.Runtime.onConsoleAPICalled(null);157    await Protocol.Debugger.disable();158    await Protocol.Runtime.disable();159  },160  async function testProfile() {161    await Protocol.Profiler.enable();162    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: 'profile', includeCommandLineAPI: true}));163    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: 'profileEnd', includeCommandLineAPI: true}));164    Protocol.Runtime.evaluate({expression: 'profile(42)', includeCommandLineAPI: true});165    InspectorTest.logMessage(await Protocol.Profiler.onceConsoleProfileStarted());166    Protocol.Runtime.evaluate({expression: 'profileEnd(42)', includeCommandLineAPI: true});167    let message = await Protocol.Profiler.onceConsoleProfileFinished();168    message.params.profile = '<profile>';169    InspectorTest.logMessage(message);170    Protocol.Runtime.evaluate({171      expression: 'this.profile = profile; this.profileEnd = profileEnd;', includeCommandLineAPI: true});172    Protocol.Runtime.evaluate({expression: 'this.profile(239)'});173    InspectorTest.logMessage(await Protocol.Profiler.onceConsoleProfileStarted());174    Protocol.Runtime.evaluate({expression: 'this.profileEnd(239)'});175    message = await Protocol.Profiler.onceConsoleProfileFinished();176    message.params.profile = '<profile>';177    InspectorTest.logMessage(message);178    await Protocol.Profiler.disable();179  },180  async function testDir() {181    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: 'dir', includeCommandLineAPI: true}));182    await Protocol.Runtime.enable();183    Protocol.Runtime.evaluate({expression: 'dir({})', includeCommandLineAPI: true});184    InspectorTest.logMessage(await Protocol.Runtime.onceConsoleAPICalled());185    Protocol.Runtime.evaluate({expression: 'dir(42)', includeCommandLineAPI: true});186    InspectorTest.logMessage(await Protocol.Runtime.onceConsoleAPICalled());187    Protocol.Runtime.evaluate({expression: 'this.dir = dir', includeCommandLineAPI: true});188    Protocol.Runtime.evaluate({expression: 'this.dir({})'});189    InspectorTest.logMessage(await Protocol.Runtime.onceConsoleAPICalled());190    await Protocol.Runtime.disable();191  },192  async function testDirXML() {193    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: 'dirxml', includeCommandLineAPI: true}));194    await Protocol.Runtime.enable();195    Protocol.Runtime.evaluate({expression: 'dirxml({})', includeCommandLineAPI: true});196    InspectorTest.logMessage(await Protocol.Runtime.onceConsoleAPICalled());197    Protocol.Runtime.evaluate({expression: 'dirxml(42)', includeCommandLineAPI: true});198    InspectorTest.logMessage(await Protocol.Runtime.onceConsoleAPICalled());199    await Protocol.Runtime.disable();200  },201  async function testTable() {202    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: 'table', includeCommandLineAPI: true}));203    await Protocol.Runtime.enable();204    Protocol.Runtime.evaluate({expression: 'table({})', includeCommandLineAPI: true});205    InspectorTest.logMessage(await Protocol.Runtime.onceConsoleAPICalled());206    Protocol.Runtime.evaluate({expression: 'table(42)', includeCommandLineAPI: true});207    InspectorTest.logMessage(await Protocol.Runtime.onceConsoleAPICalled());208    await Protocol.Runtime.disable();209  },210  async function testClear() {211    InspectorTest.logMessage(await Protocol.Runtime.evaluate({expression: 'clear', includeCommandLineAPI: true}));212    await Protocol.Runtime.enable();213    Protocol.Runtime.evaluate({expression: 'clear()', includeCommandLineAPI: true});214    InspectorTest.logMessage(await Protocol.Runtime.onceConsoleAPICalled());215    Protocol.Runtime.evaluate({expression: 'this.clear = clear', includeCommandLineAPI: true});216    Protocol.Runtime.evaluate({expression: 'this.clear()'});217    InspectorTest.logMessage(await Protocol.Runtime.onceConsoleAPICalled());218    await Protocol.Runtime.disable();219  }220]);221async function isEqual(objectId1, objectId2) {222  return (await Protocol.Runtime.callFunctionOn({223    objectId: objectId1,224    functionDeclaration: 'function(arg){return this === arg;}',225    returnByValue: true,226    arguments: [{objectId: objectId2}]227  })).result.result.value;...stepping-with-natives-and-frameworks.js
Source:stepping-with-natives-and-frameworks.js  
1// Copyright 2017 the V8 project authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4let {session, contextGroup, Protocol} = InspectorTest.start('Stepping with natives and frameworks.');5contextGroup.addScript(`6function callAll() {7  for (var f of arguments)8    f();9}10//# sourceURL=framework.js`);11session.setupScriptMap();12InspectorTest.logProtocolCommandCalls('Debugger.pause');13InspectorTest.logProtocolCommandCalls('Debugger.stepInto');14InspectorTest.logProtocolCommandCalls('Debugger.stepOver');15InspectorTest.logProtocolCommandCalls('Debugger.stepOut');16InspectorTest.logProtocolCommandCalls('Debugger.resume');17Protocol.Debugger.enable();18Protocol.Debugger.setBlackboxPatterns({patterns: ['framework\.js']});19InspectorTest.runAsyncTestSuite([20  async function testNativeCodeStepOut() {21    Protocol.Debugger.pause();22    Protocol.Runtime.evaluate({expression: '[1,2].map(v => v);'});23    await logPauseLocation(await Protocol.Debugger.oncePaused());24    Protocol.Debugger.stepInto();25    await logPauseLocation(await Protocol.Debugger.oncePaused());26    Protocol.Debugger.stepOut();27    await logPauseLocation(await Protocol.Debugger.oncePaused());28    await Protocol.Debugger.resume();29  },30  async function testNativeCodeStepOver() {31    Protocol.Debugger.pause();32    Protocol.Runtime.evaluate({expression: '[1,2].map(v => v);'});33    await logPauseLocation(await Protocol.Debugger.oncePaused());34    Protocol.Debugger.stepInto();35    await logPauseLocation(await Protocol.Debugger.oncePaused());36    Protocol.Debugger.stepOver();37    await logPauseLocation(await Protocol.Debugger.oncePaused());38    Protocol.Debugger.stepOver();39    await logPauseLocation(await Protocol.Debugger.oncePaused());40    Protocol.Debugger.stepOver();41    await logPauseLocation(await Protocol.Debugger.oncePaused());42    Protocol.Debugger.stepOver();43    await logPauseLocation(await Protocol.Debugger.oncePaused());44    await Protocol.Debugger.resume();45  },46  async function testNativeCodeStepInto() {47    Protocol.Debugger.pause();48    Protocol.Runtime.evaluate({expression: '[1,2].map(v => v);'});49    await logPauseLocation(await Protocol.Debugger.oncePaused());50    Protocol.Debugger.stepInto();51    await logPauseLocation(await Protocol.Debugger.oncePaused());52    Protocol.Debugger.stepInto();53    await logPauseLocation(await Protocol.Debugger.oncePaused());54    Protocol.Debugger.stepInto();55    await logPauseLocation(await Protocol.Debugger.oncePaused());56    Protocol.Debugger.stepInto();57    await logPauseLocation(await Protocol.Debugger.oncePaused());58    Protocol.Debugger.stepInto();59    await logPauseLocation(await Protocol.Debugger.oncePaused());60    await Protocol.Debugger.resume();61  },62  async function testFrameworkCodeStepInto() {63    Protocol.Debugger.pause();64    Protocol.Runtime.evaluate({expression: 'callAll(() => 1, () => 2);'});65    await logPauseLocation(await Protocol.Debugger.oncePaused());66    Protocol.Debugger.stepInto();67    await logPauseLocation(await Protocol.Debugger.oncePaused());68    Protocol.Debugger.stepInto();69    await logPauseLocation(await Protocol.Debugger.oncePaused());70    Protocol.Debugger.stepInto();71    await logPauseLocation(await Protocol.Debugger.oncePaused());72    Protocol.Debugger.stepInto();73    await logPauseLocation(await Protocol.Debugger.oncePaused());74    Protocol.Debugger.stepInto();75    await logPauseLocation(await Protocol.Debugger.oncePaused());76    await Protocol.Debugger.resume();77  },78  async function testFrameworkCodeStepOver() {79    Protocol.Debugger.pause();80    Protocol.Runtime.evaluate({expression: 'callAll(() => 1, () => 2);'});81    await logPauseLocation(await Protocol.Debugger.oncePaused());82    Protocol.Debugger.stepInto();83    await logPauseLocation(await Protocol.Debugger.oncePaused());84    Protocol.Debugger.stepOver();85    await logPauseLocation(await Protocol.Debugger.oncePaused());86    Protocol.Debugger.stepOver();87    await logPauseLocation(await Protocol.Debugger.oncePaused());88    Protocol.Debugger.stepOver();89    await logPauseLocation(await Protocol.Debugger.oncePaused());90    Protocol.Debugger.stepOver();91    await logPauseLocation(await Protocol.Debugger.oncePaused());92    await Protocol.Debugger.resume();93  },94  async function testFrameworkCodeStepOut() {95    Protocol.Debugger.pause();96    Protocol.Runtime.evaluate({expression: 'callAll(() => 1, () => 2);'});97    await logPauseLocation(await Protocol.Debugger.oncePaused());98    Protocol.Debugger.stepInto();99    await logPauseLocation(await Protocol.Debugger.oncePaused());100    Protocol.Debugger.stepOut();101    await logPauseLocation(await Protocol.Debugger.oncePaused());102    Protocol.Debugger.stepOut();103    await logPauseLocation(await Protocol.Debugger.oncePaused());104    await Protocol.Debugger.resume();105  },106  async function testFrameworkNextCallDeeperStepOut() {107    Protocol.Debugger.pause();108    Protocol.Runtime.evaluate({109      expression: 'callAll(() => 1, callAll.bind(null, () => 2));'});110    await logPauseLocation(await Protocol.Debugger.oncePaused());111    Protocol.Debugger.stepInto();112    await logPauseLocation(await Protocol.Debugger.oncePaused());113    Protocol.Debugger.stepOut();114    await logPauseLocation(await Protocol.Debugger.oncePaused());115    Protocol.Debugger.stepOut();116    await logPauseLocation(await Protocol.Debugger.oncePaused());117    await Protocol.Debugger.resume();118  },119  async function testFrameworkNextCallDeeperStepOutSameFunction() {120    await Protocol.Runtime.evaluate({expression: 'foo = () => 1'});121    Protocol.Debugger.pause();122    Protocol.Runtime.evaluate({123      expression: 'callAll(foo, callAll.bind(null, foo));'});124    await logPauseLocation(await Protocol.Debugger.oncePaused());125    Protocol.Debugger.stepInto();126    await logPauseLocation(await Protocol.Debugger.oncePaused());127    Protocol.Debugger.stepOut();128    await logPauseLocation(await Protocol.Debugger.oncePaused());129    await Protocol.Debugger.resume();130  },131  async function testFrameworkNextCallDeeperStepInto() {132    Protocol.Debugger.pause();133    Protocol.Runtime.evaluate({134      expression: 'callAll(() => 1, callAll.bind(null, () => 2));'});135    await logPauseLocation(await Protocol.Debugger.oncePaused());136    Protocol.Debugger.stepInto();137    await logPauseLocation(await Protocol.Debugger.oncePaused());138    Protocol.Debugger.stepOver();139    await logPauseLocation(await Protocol.Debugger.oncePaused());140    Protocol.Debugger.stepOver();141    await logPauseLocation(await Protocol.Debugger.oncePaused());142    Protocol.Debugger.stepOver();143    await logPauseLocation(await Protocol.Debugger.oncePaused());144    Protocol.Debugger.stepOver();145    await logPauseLocation(await Protocol.Debugger.oncePaused());146    await Protocol.Debugger.resume();147  },148  async function testFrameworkNextCallDeeperStepOver() {149    Protocol.Debugger.pause();150    Protocol.Runtime.evaluate({151      expression: 'callAll(() => 1, callAll.bind(null, () => 2));'});152    await logPauseLocation(await Protocol.Debugger.oncePaused());153    Protocol.Debugger.stepInto();154    await logPauseLocation(await Protocol.Debugger.oncePaused());155    Protocol.Debugger.stepOver();156    await logPauseLocation(await Protocol.Debugger.oncePaused());157    Protocol.Debugger.stepOver();158    await logPauseLocation(await Protocol.Debugger.oncePaused());159    Protocol.Debugger.stepOver();160    await logPauseLocation(await Protocol.Debugger.oncePaused());161    Protocol.Debugger.stepOver();162    await logPauseLocation(await Protocol.Debugger.oncePaused());163    await Protocol.Debugger.resume();164  },165  async function testFrameworkCurrentCallDeeperStepOut() {166    Protocol.Debugger.pause();167    Protocol.Runtime.evaluate({168      expression: 'callAll(callAll.bind(null, () => 1), () => 2);'});169    await logPauseLocation(await Protocol.Debugger.oncePaused());170    Protocol.Debugger.stepInto();171    await logPauseLocation(await Protocol.Debugger.oncePaused());172    Protocol.Debugger.stepOut();173    await logPauseLocation(await Protocol.Debugger.oncePaused());174    Protocol.Debugger.stepOut();175    await logPauseLocation(await Protocol.Debugger.oncePaused());176    await Protocol.Debugger.resume();177  },178  async function testFrameworkCurrentCallDeeperStepOutSameFunction() {179    await Protocol.Runtime.evaluate({expression: 'foo = () => 1'});180    Protocol.Debugger.pause();181    Protocol.Runtime.evaluate({182      expression: 'callAll(callAll.bind(null, foo), foo);'});183    await logPauseLocation(await Protocol.Debugger.oncePaused());184    Protocol.Debugger.stepInto();185    await logPauseLocation(await Protocol.Debugger.oncePaused());186    Protocol.Debugger.stepOut();187    await logPauseLocation(await Protocol.Debugger.oncePaused());188    await Protocol.Debugger.resume();189  },190  async function testFrameworkCurrentCallDeeperStepOver() {191    Protocol.Debugger.pause();192    Protocol.Runtime.evaluate({193      expression: 'callAll(callAll.bind(null, () => 1), () => 2);'});194    await logPauseLocation(await Protocol.Debugger.oncePaused());195    Protocol.Debugger.stepInto();196    await logPauseLocation(await Protocol.Debugger.oncePaused());197    Protocol.Debugger.stepOver();198    await logPauseLocation(await Protocol.Debugger.oncePaused());199    Protocol.Debugger.stepOver();200    await logPauseLocation(await Protocol.Debugger.oncePaused());201    Protocol.Debugger.stepOver();202    await logPauseLocation(await Protocol.Debugger.oncePaused());203    Protocol.Debugger.stepOver();204    await logPauseLocation(await Protocol.Debugger.oncePaused());205    await Protocol.Debugger.resume();206  },207  async function testFrameworkCurrentCallDeeperStepInto() {208    Protocol.Debugger.pause();209    Protocol.Runtime.evaluate({210      expression: 'callAll(callAll.bind(null, () => 1), () => 2);'});211    await logPauseLocation(await Protocol.Debugger.oncePaused());212    Protocol.Debugger.stepInto();213    await logPauseLocation(await Protocol.Debugger.oncePaused());214    Protocol.Debugger.stepInto();215    await logPauseLocation(await Protocol.Debugger.oncePaused());216    Protocol.Debugger.stepInto();217    await logPauseLocation(await Protocol.Debugger.oncePaused());218    Protocol.Debugger.stepInto();219    await logPauseLocation(await Protocol.Debugger.oncePaused());220    Protocol.Debugger.stepInto();221    await logPauseLocation(await Protocol.Debugger.oncePaused());222    await Protocol.Debugger.resume();223  },224  async function testFrameworkStepOverMixed() {225    await Protocol.Runtime.evaluate({expression: 'foo = () => 1'});226    Protocol.Debugger.pause();227    Protocol.Runtime.evaluate({228      expression: 'callAll(foo, foo, () => 2);'});229    await logPauseLocation(await Protocol.Debugger.oncePaused());230    Protocol.Debugger.stepInto();231    await logPauseLocation(await Protocol.Debugger.oncePaused());232    Protocol.Debugger.stepOver();233    await logPauseLocation(await Protocol.Debugger.oncePaused());234    Protocol.Debugger.stepOver();235    await logPauseLocation(await Protocol.Debugger.oncePaused());236    Protocol.Debugger.stepOver();237    await logPauseLocation(await Protocol.Debugger.oncePaused());238    Protocol.Debugger.stepOver();239    await logPauseLocation(await Protocol.Debugger.oncePaused());240    Protocol.Debugger.stepOver();241    await logPauseLocation(await Protocol.Debugger.oncePaused());242    Protocol.Debugger.stepOver();243    await logPauseLocation(await Protocol.Debugger.oncePaused());244    await Protocol.Debugger.resume();245  },246  async function testFrameworkStepOutMixed() {247    await Protocol.Runtime.evaluate({expression: 'foo = () => 1'});248    Protocol.Debugger.pause();249    Protocol.Runtime.evaluate({250      expression: 'callAll(foo, foo, () => 2);'});251    await logPauseLocation(await Protocol.Debugger.oncePaused());252    Protocol.Debugger.stepInto();253    await logPauseLocation(await Protocol.Debugger.oncePaused());254    Protocol.Debugger.stepOut();255    await logPauseLocation(await Protocol.Debugger.oncePaused());256    Protocol.Debugger.stepOut();257    await logPauseLocation(await Protocol.Debugger.oncePaused());258    await Protocol.Debugger.resume();259  },260  async function testStepOutFrameworkSameFunctionAtReturn() {261    await Protocol.Runtime.evaluate({expression: 'foo = () => 1'});262    Protocol.Debugger.pause();263    Protocol.Runtime.evaluate({264      expression: 'callAll(foo, foo, () => 2);'});265    await logPauseLocation(await Protocol.Debugger.oncePaused());266    Protocol.Debugger.stepInto();267    await logPauseLocation(await Protocol.Debugger.oncePaused());268    Protocol.Debugger.stepOver();269    await logPauseLocation(await Protocol.Debugger.oncePaused());270    Protocol.Debugger.stepOut();271    await logPauseLocation(await Protocol.Debugger.oncePaused());272    Protocol.Debugger.stepOut();273    await logPauseLocation(await Protocol.Debugger.oncePaused());274    await Protocol.Debugger.resume();275  }276]);277function logPauseLocation(message) {278  return session.logSourceLocation(message.params.callFrames[0].location);...coverage-block.js
Source:coverage-block.js  
1// Copyright 2017 the V8 project authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4// Flags: --allow-natives-syntax --no-always-opt --opt5// Flags: --no-stress-flush-bytecode6// Flags: --no-stress-incremental-marking7var source =8`9function fib(x) {10  if (x < 2) return 1;11  return fib(x-1) + fib(x-2);12}13function is_optimized(f) {14  return (%GetOptimizationStatus(f) & 16) ? "optimized" : "unoptimized";15}16(function iife() {17  return 1;18})();19fib(5);20`;21var break_source =22`23function g() {24  debugger;25}26function f(x) {27  if (x == 0) g();28  else f(x - 1);29}30function h() {31  g();32}33f(3);34`;35var nested =36`37var f = (function outer() {38  function nested_0() {39    return function nested_1() {40      return function nested_2() {41        return function nested_3() {}42      }43    }44  }45  function nested_4() {}46  return nested_0();47})();48f()()();49`;50let {session, contextGroup, Protocol} = InspectorTest.start("Test collecting code coverage data with Profiler.collectCoverage.");51function ClearAndGC() {52  return Protocol.Runtime.evaluate({ expression: "fib = g = f = h = is_optimized = null;" })53             .then(GC);54}55function GC() {56  return Protocol.HeapProfiler.collectGarbage();57}58function LogSorted(message) {59  message.result.result.sort((a, b) => parseInt(a.scriptId) - parseInt(b.scriptId));60  return InspectorTest.logMessage(message);61}62InspectorTest.runTestSuite([63  function testPreciseCountBaseline(next)64  {65    Protocol.Runtime.enable()66      .then(() => Protocol.Runtime.compileScript({ expression: source, sourceURL: arguments.callee.name, persistScript: true }))67      .then((result) => Protocol.Runtime.runScript({ scriptId: result.result.scriptId }))68      .then(GC)69      .then(Protocol.Profiler.enable)70      .then(() => Protocol.Profiler.startPreciseCoverage({callCount: true, detailed: true}))71      .then(Protocol.Profiler.takePreciseCoverage)72      .then(LogSorted)73      .then(Protocol.Profiler.takePreciseCoverage)74      .then(LogSorted)75      .then(Protocol.Profiler.stopPreciseCoverage)76      .then(Protocol.Profiler.disable)77      .then(Protocol.Runtime.disable)78      .then(ClearAndGC)79      .then(next);80  },81  function testPreciseCountCoverage(next)82  {83    Protocol.Runtime.enable()84      .then(Protocol.Profiler.enable)85      .then(() => Protocol.Profiler.startPreciseCoverage({callCount: true, detailed: true}))86      .then(() => Protocol.Runtime.compileScript({ expression: source, sourceURL: arguments.callee.name, persistScript: true }))87      .then((result) => Protocol.Runtime.runScript({ scriptId: result.result.scriptId }))88      .then(InspectorTest.logMessage)89      .then(ClearAndGC)90      .then(Protocol.Profiler.takePreciseCoverage)91      .then(LogSorted)92      .then(Protocol.Profiler.takePreciseCoverage)93      .then(LogSorted)94      .then(Protocol.Profiler.stopPreciseCoverage)95      .then(Protocol.Profiler.disable)96      .then(Protocol.Runtime.disable)97      .then(ClearAndGC)98      .then(next);99  },100  function testPreciseCountCoverageIncremental(next)101  {102    Protocol.Runtime.enable()103      .then(Protocol.Profiler.enable)104      .then(() => Protocol.Profiler.startPreciseCoverage({callCount: true, detailed: true}))105      .then(() => Protocol.Runtime.compileScript({ expression: source, sourceURL: arguments.callee.name, persistScript: true }))106      .then((result) => Protocol.Runtime.runScript({ scriptId: result.result.scriptId }))107      .then(InspectorTest.logMessage)108      .then(Protocol.Profiler.takePreciseCoverage)109      .then(LogSorted)110      .then(() => Protocol.Runtime.evaluate({ expression: "is_optimized(fib)" }))111      .then(message => InspectorTest.logMessage(message))112      .then(() => Protocol.Runtime.evaluate({ expression: "fib(20)" }))113      .then(message => InspectorTest.logMessage(message))114      .then(() => Protocol.Runtime.evaluate({ expression: "is_optimized(fib)" }))115      .then(message => InspectorTest.logMessage(message))116      .then(Protocol.Profiler.takePreciseCoverage)117      .then(LogSorted)118      .then(Protocol.Profiler.stopPreciseCoverage)119      .then(Protocol.Profiler.disable)120      .then(Protocol.Runtime.disable)121      .then(ClearAndGC)122      .then(next);123  },124  function testPreciseCoverageFail(next)125  {126    Protocol.Runtime.enable()127      .then(Protocol.Profiler.enable)128      .then(() => Protocol.Runtime.compileScript({ expression: source, sourceURL: arguments.callee.name, persistScript: true }))129      .then((result) => Protocol.Runtime.runScript({ scriptId: result.result.scriptId }))130      .then(InspectorTest.logMessage)131      .then(ClearAndGC)132      .then(Protocol.Profiler.takePreciseCoverage)133      .then(InspectorTest.logMessage)134      .then(Protocol.Profiler.disable)135      .then(Protocol.Runtime.disable)136      .then(ClearAndGC)137      .then(next);138  },139  function testBestEffortCoverage(next)140  {141    Protocol.Runtime.enable()142      .then(() => Protocol.Runtime.compileScript({ expression: source, sourceURL: arguments.callee.name, persistScript: true }))143      .then((result) => Protocol.Runtime.runScript({ scriptId: result.result.scriptId }))144      .then(InspectorTest.logMessage)145      .then(ClearAndGC)146      .then(Protocol.Profiler.getBestEffortCoverage)147      .then(LogSorted)148      .then(Protocol.Profiler.getBestEffortCoverage)149      .then(LogSorted)150      .then(Protocol.Runtime.disable)151      .then(ClearAndGC)152      .then(next);153  },154  function testBestEffortCoverageWithPreciseBinaryEnabled(next)155  {156    Protocol.Runtime.enable()157    .then(Protocol.Profiler.enable)158    .then(() => Protocol.Profiler.startPreciseCoverage({detailed: true}))159    .then(() => Protocol.Runtime.compileScript({ expression: source, sourceURL: arguments.callee.name, persistScript: true }))160    .then((result) => Protocol.Runtime.runScript({ scriptId: result.result.scriptId }))161    .then(InspectorTest.logMessage)162    .then(ClearAndGC)163    .then(Protocol.Profiler.getBestEffortCoverage)164    .then(LogSorted)165    .then(Protocol.Profiler.getBestEffortCoverage)166    .then(LogSorted)167    .then(ClearAndGC)168    .then(Protocol.Profiler.stopPreciseCoverage)169    .then(Protocol.Profiler.disable)170    .then(Protocol.Runtime.disable)171    .then(ClearAndGC)172    .then(next);173  },174  function testBestEffortCoverageWithPreciseCountEnabled(next)175  {176    Protocol.Runtime.enable()177      .then(Protocol.Profiler.enable)178      .then(() => Protocol.Profiler.startPreciseCoverage({callCount: true, detailed: true}))179      .then(() => Protocol.Runtime.compileScript({ expression: source, sourceURL: arguments.callee.name, persistScript: true }))180      .then((result) => Protocol.Runtime.runScript({ scriptId: result.result.scriptId }))181      .then(InspectorTest.logMessage)182      .then(ClearAndGC)183      .then(Protocol.Profiler.getBestEffortCoverage)184      .then(LogSorted)185      .then(Protocol.Profiler.getBestEffortCoverage)186      .then(LogSorted)187      .then(ClearAndGC)188      .then(Protocol.Profiler.stopPreciseCoverage)189      .then(Protocol.Profiler.disable)190      .then(Protocol.Runtime.disable)191      .then(ClearAndGC)192      .then(next);193  },194  function testEnablePreciseCountCoverageAtPause(next)195  {196    function handleDebuggerPause() {197      Protocol.Profiler.enable()198          .then(() => Protocol.Profiler.startPreciseCoverage({callCount: true, detailed: true}))199          .then(Protocol.Debugger.resume)200    }201    Protocol.Debugger.enable();202    Protocol.Debugger.oncePaused().then(handleDebuggerPause);203    Protocol.Runtime.enable()204      .then(() => Protocol.Runtime.compileScript({ expression: break_source, sourceURL: arguments.callee.name, persistScript: true }))205      .then((result) => Protocol.Runtime.runScript({ scriptId: result.result.scriptId }))206      .then(InspectorTest.logMessage)207      .then(ClearAndGC)208      .then(Protocol.Profiler.takePreciseCoverage)209      .then(LogSorted)210      .then(ClearAndGC)211      .then(Protocol.Profiler.stopPreciseCoverage)212      .then(Protocol.Profiler.disable)213      .then(Protocol.Runtime.disable)214      .then(Protocol.Debugger.disable)215      .then(ClearAndGC)216      .then(next);217  },218  function testPreciseBinaryCoverage(next)219  {220    Protocol.Runtime.enable()221      .then(Protocol.Profiler.enable)222      .then(() => Protocol.Profiler.startPreciseCoverage({detailed: true}))223      .then(() => Protocol.Runtime.compileScript({ expression: source, sourceURL: arguments.callee.name, persistScript: true }))224      .then((result) => Protocol.Runtime.runScript({ scriptId: result.result.scriptId }))225      .then(InspectorTest.logMessage)226      .then(Protocol.Profiler.takePreciseCoverage)227      .then(LogSorted)228      .then(() => Protocol.Runtime.evaluate({ expression: "is_optimized(fib)" }))229      .then(message => InspectorTest.logMessage(message))230      .then(() => Protocol.Runtime.evaluate({ expression: "fib(20)" }))231      .then(message => InspectorTest.logMessage(message))232      .then(() => Protocol.Runtime.evaluate({ expression: "is_optimized(fib)" }))233      .then(message => InspectorTest.logMessage(message))234      .then(Protocol.Profiler.takePreciseCoverage)235      .then(LogSorted)236      .then(Protocol.Profiler.stopPreciseCoverage)237      .then(Protocol.Profiler.disable)238      .then(Protocol.Runtime.disable)239      .then(ClearAndGC)240      .then(next);241  },242  function testPreciseEmptyScriptCoverageEntries(next)243  {244    // Enabling the debugger holds onto script objects even though its245    // functions can be garbage collected. We would get empty ScriptCoverage246    // entires unless we remove them.247    Protocol.Debugger.enable()248      .then(Protocol.Runtime.enable)249      .then(() => Protocol.Runtime.compileScript({ expression: source, sourceURL: arguments.callee.name, persistScript: true }))250      .then((result) => Protocol.Runtime.runScript({ scriptId: result.result.scriptId }))251      .then(ClearAndGC)252      .then(Protocol.Profiler.enable)253      .then(() => Protocol.Profiler.startPreciseCoverage({detailed: true}))254      .then(Protocol.Profiler.takePreciseCoverage)255      .then(LogSorted)256      .then(Protocol.Profiler.stopPreciseCoverage)257      .then(Protocol.Profiler.disable)258      .then(Protocol.Runtime.disable)259      .then(Protocol.Debugger.disable)260      .then(ClearAndGC)261      .then(next);262  },263  function testPreciseCountCoveragePartial(next)264  {265    Protocol.Runtime.enable()266      .then(Protocol.Profiler.enable)267      .then(() => Protocol.Profiler.startPreciseCoverage({callCount: true, detailed: true}))268      .then(() => Protocol.Runtime.compileScript({ expression: nested, sourceURL: arguments.callee.name, persistScript: true }))269      .then((result) => Protocol.Runtime.runScript({ scriptId: result.result.scriptId }))270      .then(InspectorTest.logMessage)271      .then(Protocol.Profiler.takePreciseCoverage)272      .then(LogSorted)273      .then(() => Protocol.Runtime.evaluate({ expression: "f()" }))274      .then(Protocol.Profiler.takePreciseCoverage)275      .then(LogSorted)276      .then(Protocol.Profiler.stopPreciseCoverage)277      .then(Protocol.Profiler.disable)278      .then(Protocol.Runtime.disable)279      .then(ClearAndGC)280      .then(next);281  },...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!!
