How to use _write method in Cypress

Best JavaScript code snippet using cypress

jscex-jit.js

Source:jscex-jit.js Github

copy

Full Screen

...506                return this;507            },508509            _writeLine: function (s) {510                this._write(s)._write("\n");511                return this;512            },513514            _writeIndents: function () {515                for (var i = 0; i < this._indent; i++) {516                    this._write(" ");517                }518519                for (var i = 0; i < this._indentLevel; i++) {520                    this._write("    ");521                }522                return this;523            },524525            generate: function (params, jscexAst) {526                this._buffer = [];527528                this._writeLine("(function (" + params.join(", ") + ") {");529                this._indentLevel++;530531                this._writeIndents()532                    ._writeLine("var " + this._builderVar + " = Jscex.builders[" + stringify(this._builderName) + "];");533534                this._writeIndents()535                    ._writeLine("return " + this._builderVar + ".Start(this,");536                this._indentLevel++;537538                this._pos = { };539540                this._writeIndents()541                    ._visitJscex(jscexAst)542                    ._writeLine();543                this._indentLevel--;544545                this._writeIndents()546                    ._writeLine(");");547                this._indentLevel--;548549                this._writeIndents()550                    ._write("})");551552                return this._buffer.join("");553            },554555            _visitJscex: function (ast) {556                this._jscexVisitors[ast.type].call(this, ast);557                return this;558            },559560            _visitRaw: function (ast) {561                var type = ast[0];562563                function throwUnsupportedError() {564                    throw new Error('"' + type + '" is not currently supported.');565                }566567                var visitor = this._rawVisitors[type];568569                if (visitor) {570                    visitor.call(this, ast);571                } else {572                    throwUnsupportedError();573                }574575                return this;576            },577578            _visitJscexStatements: function (statements) {579                for (var i = 0; i < statements.length; i++) {580                    var stmt = statements[i];581582                    if (stmt.type == "raw" || stmt.type == "if" || stmt.type == "switch") {583                        this._writeIndents()584                            ._visitJscex(stmt)._writeLine();585                    } else if (stmt.type == "delay") {586                        this._visitJscexStatements(stmt.stmts);587                    } else {588                        this._writeIndents()589                            ._write("return ")._visitJscex(stmt)._writeLine(";");590                    }591                }592            },593594            _visitRawStatements: function (statements) {595                for (var i = 0; i < statements.length; i++) {596                    var s = statements[i];597598                    this._writeIndents()599                        ._visitRaw(s)._writeLine();600601                    switch (s[0]) {602                        case "break":603                        case "return":604                        case "continue":605                        case "throw":606                            return;607                    }608                }609            },610611            _visitRawBody: function (body) {612                if (body[0] == "block") {613                    this._visitRaw(body);614                } else {615                    this._writeLine();616                    this._indentLevel++;617618                    this._writeIndents()619                        ._visitRaw(body);620                    this._indentLevel--;621                }622623                return this;624            },625626            _visitRawFunction: function (ast) {627                var funcName = ast[1] || "";628                var args = ast[2];629                var statements = ast[3];630                631                this._writeLine("function " + funcName + "(" + args.join(", ") + ") {")632                this._indentLevel++;633634                var currInFunction = this._pos.inFunction;635                this._pos.inFunction = true;636637                this._visitRawStatements(statements);638                this._indentLevel--;639640                this._pos.inFunction = currInFunction;641642                this._writeIndents()643                    ._write("}");644            },645646            _jscexVisitors: {647                "delay": function (ast) {648                    if (ast.stmts.length == 1) {649                        var subStmt = ast.stmts[0];650                        switch (subStmt.type) {651                            case "delay":652                            case "combine":653                            case "normal":654                            case "break":655                            case "continue":656                            case "loop":657                            case "try":658                                this._visitJscex(subStmt);659                                return;660                            case "return":661                                if (!subStmt.stmt[1]) {662                                    this._visitJscex(subStmt);663                                    return;664                                }665                        }666                    }667668                    this._writeLine(this._builderVar + ".Delay(function () {");669                    this._indentLevel++;670671                    this._visitJscexStatements(ast.stmts);672                    this._indentLevel--;673674                    this._writeIndents()675                        ._write("})");676                },677678                "combine": function (ast) {679                    this._writeLine(this._builderVar + ".Combine(");680                    this._indentLevel++;681682                    this._writeIndents()683                        ._visitJscex(ast.first)._writeLine(",");684                    this._writeIndents()685                        ._visitJscex(ast.second)._writeLine();686                    this._indentLevel--;687688                    this._writeIndents()689                        ._write(")");690                },691692                "loop": function (ast) {693                    this._writeLine(this._builderVar + ".Loop(");694                    this._indentLevel++;695696                    if (ast.condition) {697                        this._writeIndents()698                            ._writeLine("function () {");699                        this._indentLevel++;700701                        this._writeIndents()702                            ._write("return ")._visitRaw(ast.condition)._writeLine(";");703                        this._indentLevel--;704705                        this._writeIndents()706                            ._writeLine("},");707                    } else {708                        this._writeIndents()._writeLine("null,");709                    }710711                    if (ast.update) {712                        this._writeIndents()713                            ._writeLine("function () {");714                        this._indentLevel++;715716                        this._writeIndents()717                            ._visitRaw(ast.update)._writeLine(";");718                        this._indentLevel--;719720                        this._writeIndents()721                            ._writeLine("},");722                    } else {723                        this._writeIndents()._writeLine("null,");724                    }725726                    this._writeIndents()727                        ._visitJscex(ast.bodyStmt)._writeLine(",");728729                    this._writeIndents()730                        ._writeLine(ast.bodyFirst);731                    this._indentLevel--;732733                    this._writeIndents()734                        ._write(")");735                },736737                "raw": function (ast) {738                    this._visitRaw(ast.stmt);739                },740741                "bind": function (ast) {742                    var info = ast.info;743                    this._write(this._builderVar + ".Bind(")._visitRaw(info.expression)._writeLine(", function (" + info.argName + ") {");744                    this._indentLevel++;745746                    if (info.assignee == "return") {747                        this._writeIndents()748                            ._writeLine("return " + this._builderVar + ".Return(" + info.argName + ");");749                    } else {750                        if (info.assignee) {751                            this._writeIndents()752                                ._visitRaw(info.assignee)._writeLine(" = " + info.argName + ";");753                        }754755                        this._visitJscexStatements(ast.stmts);756                    }757                    this._indentLevel--;758759                    this._writeIndents()760                        ._write("})");761                },762763                "if": function (ast) {764765                    for (var i = 0; i < ast.conditionStmts.length; i++) {766                        var stmt = ast.conditionStmts[i];767                        768                        this._write("if (")._visitRaw(stmt.cond)._writeLine(") {");769                        this._indentLevel++;770771                        this._visitJscexStatements(stmt.stmts);772                        this._indentLevel--;773774                        this._writeIndents()775                            ._write("} else ");776                    }777778                    this._writeLine("{");779                    this._indentLevel++;780781                    if (ast.elseStmts) {782                        this._visitJscexStatements(ast.elseStmts);783                    } else {784                        this._writeIndents()785                            ._writeLine("return " + this._builderVar + ".Normal();");786                    }787788                    this._indentLevel--;789790                    this._writeIndents()791                        ._write("}");792                },793794                "switch": function (ast) {795                    this._write("switch (")._visitRaw(ast.item)._writeLine(") {");796                    this._indentLevel++;797798                    for (var i = 0; i < ast.caseStmts.length; i++) {799                        var caseStmt = ast.caseStmts[i];800801                        if (caseStmt.item) {802                            this._writeIndents()803                                ._write("case ")._visitRaw(caseStmt.item)._writeLine(":");804                        } else {805                            this._writeIndents()._writeLine("default:");806                        }807                        this._indentLevel++;808809                        this._visitJscexStatements(caseStmt.stmts);810                        this._indentLevel--;811                    }812813                    this._writeIndents()814                        ._write("}");815                },816817                "try": function (ast) {818                    this._writeLine(this._builderVar + ".Try(");819                    this._indentLevel++;820821                    this._writeIndents()822                        ._visitJscex(ast.bodyStmt)._writeLine(",");823824                    if (ast.catchStmts) {825                        this._writeIndents()826                            ._writeLine("function (" + ast.exVar + ") {");827                        this._indentLevel++;828829                        this._visitJscexStatements(ast.catchStmts);830                        this._indentLevel--;831832                        this._writeIndents()833                            ._writeLine("},");834                    } else {835                        this._writeIndents()836                            ._writeLine("null,");837                    }838839                    if (ast.finallyStmt) {840                        this._writeIndents()841                            ._visitJscex(ast.finallyStmt)._writeLine();842                    } else {843                        this._writeIndents()844                            ._writeLine("null");845                    }846                    this._indentLevel--;847848                    this._writeIndents()849                        ._write(")");850                },851852                "normal": function (ast) {853                    this._write(this._builderVar + ".Normal()");854                },855856                "throw": function (ast) {857                    this._write(this._builderVar + ".Throw(")._visitRaw(ast.stmt[1])._write(")");858                },859860                "break": function (ast) {861                    this._write(this._builderVar + ".Break()");862                },863864                "continue": function (ast) {865                    this._write(this._builderVar + ".Continue()");866                },867868                "return": function (ast) {869                    this._write(this._builderVar + ".Return(");870                    if (ast.stmt[1]) this._visitRaw(ast.stmt[1]);871                    this._write(")");872                }873            },874875            _rawVisitors: {876                "var": function (ast) {877                    this._write("var ");878879                    var items = ast[1];880                    for (var i = 0; i < items.length; i++) {881                        this._write(items[i][0]);882                        if (items[i].length > 1) {883                            this._write(" = ")._visitRaw(items[i][1]);884                        }885                        if (i < items.length - 1) this._write(", ");886                    }887888                    this._write(";");889                },890891                "seq": function (ast) {892                    for (var i = 1; i < ast.length; i++) {893                        this._visitRaw(ast[i]);894                        if (i < ast.length - 1) this._write(", "); 895                    }896                },897898                "binary": function (ast) {899                    var op = ast[1], left = ast[2], right = ast[3];900901                    function needBracket(item) {902                        var type = item[0];903                        return !(type == "num" || type == "name" || type == "dot");904                    }905906                    if (needBracket(left)) {907                        this._write("(")._visitRaw(left)._write(") ");908                    } else {909                        this._visitRaw(left)._write(" ");910                    }911912                    this._write(op);913914                    if (needBracket(right)) {915                        this._write(" (")._visitRaw(right)._write(")");916                    } else {917                        this._write(" ")._visitRaw(right);918                    }919                },920921                "sub": function (ast) {922                    var prop = ast[1], index = ast[2];923924                    function needBracket() {925                        return !(prop[0] == "name")926                    }927928                    if (needBracket()) {929                        this._write("(")._visitRaw(prop)._write(")[")._visitRaw(index)._write("]");930                    } else {931                        this._visitRaw(prop)._write("[")._visitRaw(index)._write("]");932                    }933                },934935                "unary-postfix": function (ast) {936                    var op = ast[1];937                    var item = ast[2];938                    this._visitRaw(item)._write(op);939                },940941                "unary-prefix": function (ast) {942                    var op = ast[1];943                    var item = ast[2];944                    this._write(op);945                    if (op == "typeof") {946                        this._write("(")._visitRaw(item)._write(")");947                    } else {948                        this._visitRaw(item);949                    }950                },951952                "assign": function (ast) {953                    var op = ast[1];954                    var name = ast[2];955                    var value = ast[3];956957                    this._visitRaw(name);958                    if ((typeof op) == "string") {959                        this._write(" " + op + "= ");960                    } else {961                        this._write(" = ");962                    }963                    this._visitRaw(value);964                },965966                "stat": function (ast) {967                    this._visitRaw(ast[1])._write(";");968                },969970                "dot": function (ast) {971                    function needBracket() {972                        var leftOp = ast[1][0];973                        return !(leftOp == "dot" || leftOp == "name");974                    }975976                    if (needBracket()) {977                        this._write("(")._visitRaw(ast[1])._write(").")._write(ast[2]);978                    } else {979                        this._visitRaw(ast[1])._write(".")._write(ast[2]);980                    }981                },982983                "new": function (ast) {984                    var ctor = ast[1];985986                    this._write("new ")._visitRaw(ctor)._write("(");987988                    var args = ast[2];989                    for (var i = 0, len = args.length; i < len; i++) {990                        this._visitRaw(args[i]);991                        if (i < len - 1) this._write(", ");992                    }993994                    this._write(")");995                },996997                "call": function (ast) {998                999                    if (_isJscexPattern(ast)) {1000                        var indent = this._indent + this._indentLevel * 4;1001                        var newCode = _compileJscexPattern(ast, indent);1002                        this._write(newCode);1003                    } else {10041005                        var invalidBind = (ast[1][0] == "name") && (ast[1][1] == this._binder);1006                        if (invalidBind) {1007                            this._pos = { inFunction: true };1008                            this._buffer = [];1009                        }10101011                        this._visitRaw(ast[1])._write("(");10121013                        var args = ast[2];1014                        for (var i = 0; i < args.length; i++) {1015                            this._visitRaw(args[i]);1016                            if (i < args.length - 1) this._write(", ");1017                        }10181019                        this._write(")");10201021                        if (invalidBind) {1022                            throw ("Invalid bind operation: " + this._buffer.join(""));1023                        }1024                    }1025                },10261027                "name": function (ast) {1028                    this._write(ast[1]);1029                },10301031                "object": function (ast) {1032                    var items = ast[1];1033                    if (items.length <= 0) {1034                        this._write("{ }");1035                    } else {1036                        this._writeLine("{");1037                        this._indentLevel++;1038                        1039                        for (var i = 0; i < items.length; i++) {1040                            this._writeIndents()1041                                ._write(stringify(items[i][0]) + ": ")1042                                ._visitRaw(items[i][1]);1043                            1044                            if (i < items.length - 1) {1045                                this._writeLine(",");1046                            } else {1047                                this._writeLine("");1048                            }1049                        }1050                        1051                        this._indentLevel--;1052                        this._writeIndents()._write("}");1053                    }1054                },10551056                "array": function (ast) {1057                    this._write("[");10581059                    var items = ast[1];1060                    for (var i = 0; i < items.length; i++) {1061                        this._visitRaw(items[i]);1062                        if (i < items.length - 1) this._write(", ");1063                    }10641065                    this._write("]");1066                },10671068                "num": function (ast) {1069                    this._write(ast[1]);1070                },10711072                "regexp": function (ast) {1073                    this._write("/" + ast[1] + "/" + ast[2]);1074                },10751076                "string": function (ast) {1077                    this._write(stringify(ast[1]));1078                },10791080                "function": function (ast) {1081                    this._visitRawFunction(ast);1082                },10831084                "defun": function (ast) {1085                    this._visitRawFunction(ast);1086                },10871088                "return": function (ast) {1089                    if (this._pos.inFunction) {1090                        this._write("return");1091                        var value = ast[1];1092                        if (value) this._write(" ")._visitRaw(value);1093                        this._write(";");1094                    } else {1095                        this._write("return ")._visitJscex({ type: "return", stmt: ast })._write(";");1096                    }1097                },1098                1099                "for": function (ast) {1100                    this._write("for (");11011102                    var setup = ast[1];1103                    if (setup) {1104                        this._visitRaw(setup);1105                        if (setup[0] != "var") {1106                            this._write("; ");1107                        } else {1108                            this._write(" ");1109                        }1110                    } else {1111                        this._write("; ");1112                    }11131114                    var condition = ast[2];1115                    if (condition) this._visitRaw(condition);1116                    this._write("; ");11171118                    var update = ast[3];1119                    if (update) this._visitRaw(update);1120                    this._write(") ");11211122                    var currInLoop = this._pos.inLoop;1123                    this._pos.inLoop = true;11241125                    var body = ast[4];1126                    this._visitRawBody(body);11271128                    this._pos.inLoop = currInLoop;1129                },11301131                "for-in": function (ast) {1132                    this._write("for (");11331134                    var declare = ast[1];1135                    if (declare[0] == "var") { // declare == ["var", [["m"]]]1136                        this._write("var " + declare[1][0][0]);1137                    } else {1138                        this._visitRaw(declare);1139                    }1140                    1141                    this._write(" in ")._visitRaw(ast[3])._write(") ");11421143                    var body = ast[4];1144                    this._visitRawBody(body);1145                },11461147                "block": function (ast) {1148                    this._writeLine("{")1149                    this._indentLevel++;11501151                    this._visitRawStatements(ast[1]);1152                    this._indentLevel--;11531154                    this._writeIndents()1155                        ._write("}");1156                },11571158                "while": function (ast) {1159                    var condition = ast[1];1160                    var body = ast[2];11611162                    var currInLoop = this._pos.inLoop1163                    this._pos.inLoop = true;11641165                    this._write("while (")._visitRaw(condition)._write(") ")._visitRawBody(body);11661167                    this._pos.inLoop = currInLoop;1168                },11691170                "do": function (ast) {1171                    var condition = ast[1];1172                    var body = ast[2];11731174                    var currInLoop = this._pos.inLoop;1175                    this._pos.inLoop = true;11761177                    this._write("do ")._visitRawBody(body);11781179                    this._pos.inLoop = currInLoop;11801181                    if (body[0] == "block") {1182                        this._write(" ");1183                    } else {1184                        this._writeLine()._writeIndents();1185                    }11861187                    this._write("while (")._visitRaw(condition)._write(");");1188                },11891190                "if": function (ast) {1191                    var condition = ast[1];1192                    var thenPart = ast[2];11931194                    this._write("if (")._visitRaw(condition)._write(") ")._visitRawBody(thenPart);11951196                    var elsePart = ast[3];1197                    if (elsePart) {1198                        if (thenPart[0] == "block") {1199                            this._write(" ");1200                        } else {1201                            this._writeLine("")1202                                ._writeIndents();1203                        }12041205                        if (elsePart[0] == "if") {1206                            this._write("else ")._visitRaw(elsePart);1207                        } else {1208                            this._write("else ")._visitRawBody(elsePart);1209                        }1210                    }1211                },12121213                "break": function (ast) {1214                    if (this._pos.inLoop || this._pos.inSwitch) {1215                        this._write("break;");1216                    } else {1217                        this._write("return ")._visitJscex({ type: "break", stmt: ast })._write(";");1218                    }1219                },12201221                "continue": function (ast) {1222                    if (this._pos.inLoop) {1223                        this._write("continue;");1224                    } else {1225                        this._write("return ")._visitJscex({ type: "continue", stmt: ast })._write(";");1226                    }1227                },12281229                "throw": function (ast) {1230                    var pos = this._pos;1231                    if (pos.inTry || pos.inFunction) {1232                        this._write("throw ")._visitRaw(ast[1])._write(";");1233                    } else {1234                        this._write("return ")._visitJscex({ type: "throw", stmt: ast })._write(";");1235                    }1236                },12371238                "conditional": function (ast) {1239                    this._write("(")._visitRaw(ast[1])._write(") ? (")._visitRaw(ast[2])._write(") : (")._visitRaw(ast[3])._write(")");1240                },12411242                "try": function (ast) {12431244                    this._writeLine("try {");1245                    this._indentLevel++;12461247                    var currInTry = this._pos.inTry;1248                    this._pos.inTry = true;12491250                    this._visitRawStatements(ast[1]);1251                    this._indentLevel--;12521253                    this._pos.inTry = currInTry;12541255                    var catchClause = ast[2];1256                    var finallyStatements = ast[3];12571258                    if (catchClause) {1259                        this._writeIndents()1260                            ._writeLine("} catch (" + catchClause[0] + ") {")1261                        this._indentLevel++;12621263                        this._visitRawStatements(catchClause[1]);1264                        this._indentLevel--;1265                    }12661267                    if (finallyStatements) {1268                        this._writeIndents()1269                            ._writeLine("} finally {");1270                        this._indentLevel++;12711272                        this._visitRawStatements(finallyStatements);1273                        this._indentLevel--;1274                    }                12751276                    this._writeIndents()1277                        ._write("}");1278                },12791280                "switch": function (ast) {1281                    this._write("switch (")._visitRaw(ast[1])._writeLine(") {");1282                    this._indentLevel++;12831284                    var currInSwitch = this._pos.inSwitch;1285                    this._pos.inSwitch = true;12861287                    var cases = ast[2];1288                    for (var i = 0; i < cases.length; i++) {1289                        var c = cases[i];1290                        this._writeIndents();12911292                        if (c[0]) {1293                            this._write("case ")._visitRaw(c[0])._writeLine(":");1294                        } else {1295                            this._writeLine("default:");1296                        }1297                        this._indentLevel++;12981299                        this._visitRawStatements(c[1]);1300                        this._indentLevel--;1301                    }1302                    this._indentLevel--;13031304                    this._pos.inSwitch = currInSwitch;13051306                    this._writeIndents()1307                        ._write("}");1308                }1309            }1310        }13111312        function _isJscexPattern(ast) {1313            if (ast[0] != "call") return false;1314            1315            var evalName = ast[1];1316            if (evalName[0] != "name" || evalName[1] != "eval") return false;13171318            var compileCall = ast[2][0];1319            if (!compileCall || compileCall[0] != "call") return false;13201321            var compileMethod = compileCall[1];
...

Full Screen

Full Screen

compiler_unparse.py

Source:compiler_unparse.py Github

copy

Full Screen

...36        self._single_func = single_line_functions37        self._do_indent = True38        self._indent = 039        self._dispatch(tree)40        self._write("\n")41        self.f.flush()42    #########################################################################43    # Unparser private interface.44    #########################################################################45    ### format, output, and dispatch methods ################################46    def _fill(self, text = ""):47        "Indent a piece of text, according to the current indentation level"48        if self._do_indent:49            self._write("\n"+"    "*self._indent + text)50        else:51            self._write(text)52    def _write(self, text):53        "Append a piece of text to the current line."54        self.f.write(text)55    def _enter(self):56        "Print ':', and increase the indentation."57        self._write(": ")58        self._indent += 159    def _leave(self):60        "Decrease the indentation level."61        self._indent -= 162    def _dispatch(self, tree):63        "_dispatcher function, _dispatching tree type T to method _T."64        if isinstance(tree, list):65            for t in tree:66                self._dispatch(t)67            return68        meth = getattr(self, "_"+tree.__class__.__name__)69        if tree.__class__.__name__ == 'NoneType' and not self._do_indent:70            return71        meth(tree)72    #########################################################################73    # compiler.ast unparsing methods.74    #75    # There should be one method per concrete grammar type. They are76    # organized in alphabetical order.77    #########################################################################78    def _Add(self, t):79        self.__binary_op(t, '+')80    def _And(self, t):81        self._write(" (")82        for i, node in enumerate(t.nodes):83            self._dispatch(node)84            if i != len(t.nodes)-1:85                self._write(") and (")86        self._write(")")87    def _AssAttr(self, t):88        """ Handle assigning an attribute of an object89        """90        self._dispatch(t.expr)91        self._write('.'+t.attrname)92    def _Assign(self, t):93        """ Expression Assignment such as "a = 1".94            This only handles assignment in expressions.  Keyword assignment95            is handled separately.96        """97        self._fill()98        for target in t.nodes:99            self._dispatch(target)100            self._write(" = ")101        self._dispatch(t.expr)102        if not self._do_indent:103            self._write('; ')104    def _AssName(self, t):105        """ Name on left hand side of expression.106            Treat just like a name on the right side of an expression.107        """108        self._Name(t)109    def _AssTuple(self, t):110        """ Tuple on left hand side of an expression.111        """112        # _write each elements, separated by a comma.113        for element in t.nodes[:-1]:114            self._dispatch(element)115            self._write(", ")116        # Handle the last one without writing comma117        last_element = t.nodes[-1]118        self._dispatch(last_element)119    def _AugAssign(self, t):120        """ +=,-=,*=,/=,**=, etc. operations121        """122        self._fill()123        self._dispatch(t.node)124        self._write(' '+t.op+' ')125        self._dispatch(t.expr)126        if not self._do_indent:127            self._write(';')128    def _Bitand(self, t):129        """ Bit and operation.130        """131        for i, node in enumerate(t.nodes):132            self._write("(")133            self._dispatch(node)134            self._write(")")135            if i != len(t.nodes)-1:136                self._write(" & ")137    def _Bitor(self, t):138        """ Bit or operation139        """140        for i, node in enumerate(t.nodes):141            self._write("(")142            self._dispatch(node)143            self._write(")")144            if i != len(t.nodes)-1:145                self._write(" | ")146    def _CallFunc(self, t):147        """ Function call.148        """149        self._dispatch(t.node)150        self._write("(")151        comma = False152        for e in t.args:153            if comma: self._write(", ")154            else: comma = True155            self._dispatch(e)156        if t.star_args:157            if comma: self._write(", ")158            else: comma = True159            self._write("*")160            self._dispatch(t.star_args)161        if t.dstar_args:162            if comma: self._write(", ")163            else: comma = True164            self._write("**")165            self._dispatch(t.dstar_args)166        self._write(")")167    def _Compare(self, t):168        self._dispatch(t.expr)169        for op, expr in t.ops:170            self._write(" " + op + " ")171            self._dispatch(expr)172    def _Const(self, t):173        """ A constant value such as an integer value, 3, or a string, "hello".174        """175        self._dispatch(t.value)176    def _Decorators(self, t):177        """ Handle function decorators (eg. @has_units)178        """179        for node in t.nodes:180            self._dispatch(node)181    def _Dict(self, t):182        self._write("{")183        for  i, (k, v) in enumerate(t.items):184            self._dispatch(k)185            self._write(": ")186            self._dispatch(v)187            if i < len(t.items)-1:188                self._write(", ")189        self._write("}")190    def _Discard(self, t):191        """ Node for when return value is ignored such as in "foo(a)".192        """193        self._fill()194        self._dispatch(t.expr)195    def _Div(self, t):196        self.__binary_op(t, '/')197    def _Ellipsis(self, t):198        self._write("...")199    def _From(self, t):200        """ Handle "from xyz import foo, bar as baz".201        """202        # fixme: Are From and ImportFrom handled differently?203        self._fill("from ")204        self._write(t.modname)205        self._write(" import ")206        for i, (name,asname) in enumerate(t.names):207            if i != 0:208                self._write(", ")209            self._write(name)210            if asname is not None:211                self._write(" as "+asname)212    def _Function(self, t):213        """ Handle function definitions214        """215        if t.decorators is not None:216            self._fill("@")217            self._dispatch(t.decorators)218        self._fill("def "+t.name + "(")219        defaults = [None] * (len(t.argnames) - len(t.defaults)) + list(t.defaults)220        for i, arg in enumerate(zip(t.argnames, defaults)):221            self._write(arg[0])222            if arg[1] is not None:223                self._write('=')224                self._dispatch(arg[1])225            if i < len(t.argnames)-1:226                self._write(', ')227        self._write(")")228        if self._single_func:229            self._do_indent = False230        self._enter()231        self._dispatch(t.code)232        self._leave()233        self._do_indent = True234    def _Getattr(self, t):235        """ Handle getting an attribute of an object236        """237        if isinstance(t.expr, (Div, Mul, Sub, Add)):238            self._write('(')239            self._dispatch(t.expr)240            self._write(')')241        else:242            self._dispatch(t.expr)243            244        self._write('.'+t.attrname)245        246    def _If(self, t):247        self._fill()248        249        for i, (compare,code) in enumerate(t.tests):250            if i == 0:251                self._write("if ")252            else:253                self._write("elif ")254            self._dispatch(compare)255            self._enter()256            self._fill()257            self._dispatch(code)258            self._leave()259            self._write("\n")260        if t.else_ is not None:261            self._write("else")262            self._enter()263            self._fill()264            self._dispatch(t.else_)265            self._leave()266            self._write("\n")267            268    def _IfExp(self, t):269        self._dispatch(t.then)270        self._write(" if ")271        self._dispatch(t.test)272        if t.else_ is not None:273            self._write(" else (")274            self._dispatch(t.else_)275            self._write(")")276    def _Import(self, t):277        """ Handle "import xyz.foo".278        """279        self._fill("import ")280        281        for i, (name,asname) in enumerate(t.names):282            if i != 0:283                self._write(", ")284            self._write(name)285            if asname is not None:286                self._write(" as "+asname)287    def _Keyword(self, t):288        """ Keyword value assignment within function calls and definitions.289        """290        self._write(t.name)291        self._write("=")292        self._dispatch(t.expr)293        294    def _List(self, t):295        self._write("[")296        for  i,node in enumerate(t.nodes):297            self._dispatch(node)298            if i < len(t.nodes)-1:299                self._write(", ")300        self._write("]")301    def _Module(self, t):302        if t.doc is not None:303            self._dispatch(t.doc)304        self._dispatch(t.node)305    def _Mul(self, t):306        self.__binary_op(t, '*')307    def _Name(self, t):308        self._write(t.name)309    def _NoneType(self, t):310        self._write("None")311        312    def _Not(self, t):313        self._write('not (')314        self._dispatch(t.expr)315        self._write(')')316        317    def _Or(self, t):318        self._write(" (")319        for i, node in enumerate(t.nodes):320            self._dispatch(node)321            if i != len(t.nodes)-1:322                self._write(") or (")323        self._write(")")324                325    def _Pass(self, t):326        self._write("pass\n")327    def _Printnl(self, t):328        self._fill("print ")329        if t.dest:330            self._write(">> ")331            self._dispatch(t.dest)332            self._write(", ")333        comma = False334        for node in t.nodes:335            if comma: self._write(', ')336            else: comma = True337            self._dispatch(node)338    def _Power(self, t):339        self.__binary_op(t, '**')340    def _Return(self, t):341        self._fill("return ")342        if t.value:343            if isinstance(t.value, Tuple):344                text = ', '.join([ name.name for name in t.value.asList() ])345                self._write(text)346            else:347                self._dispatch(t.value)348            if not self._do_indent:349                self._write('; ')350    def _Slice(self, t):351        self._dispatch(t.expr)352        self._write("[")353        if t.lower:354            self._dispatch(t.lower)355        self._write(":")356        if t.upper:357            self._dispatch(t.upper)358        #if t.step:359        #    self._write(":")360        #    self._dispatch(t.step)361        self._write("]")362    def _Sliceobj(self, t):363        for i, node in enumerate(t.nodes):364            if i != 0:365                self._write(":")366            if not (isinstance(node, Const) and node.value is None):367                self._dispatch(node)368    def _Stmt(self, tree):369        for node in tree.nodes:370            self._dispatch(node)371    def _Sub(self, t):372        self.__binary_op(t, '-')373    def _Subscript(self, t):374        self._dispatch(t.expr)375        self._write("[")376        for i, value in enumerate(t.subs):377            if i != 0:378                self._write(",")379            self._dispatch(value)380        self._write("]")381    def _TryExcept(self, t):382        self._fill("try")383        self._enter()384        self._dispatch(t.body)385        self._leave()386        for handler in t.handlers:387            self._fill('except ')388            self._dispatch(handler[0])389            if handler[1] is not None:390                self._write(', ')391                self._dispatch(handler[1])392            self._enter()393            self._dispatch(handler[2])394            self._leave()395            396        if t.else_:397            self._fill("else")398            self._enter()399            self._dispatch(t.else_)400            self._leave()401    def _Tuple(self, t):402        if not t.nodes:403            # Empty tuple.404            self._write("()")405        else:406            self._write("(")407            # _write each elements, separated by a comma.408            for element in t.nodes[:-1]:409                self._dispatch(element)410                self._write(", ")411            # Handle the last one without writing comma412            last_element = t.nodes[-1]413            self._dispatch(last_element)414            self._write(")")415            416    def _UnaryAdd(self, t):417        self._write("+")418        self._dispatch(t.expr)419        420    def _UnarySub(self, t):421        self._write("-")422        self._dispatch(t.expr)        423    def _With(self, t):424        self._fill('with ')425        self._dispatch(t.expr)426        if t.vars:427            self._write(' as ')428            self._dispatch(t.vars.name)429        self._enter()430        self._dispatch(t.body)431        self._leave()432        self._write('\n')433        434    def _int(self, t):435        self._write(repr(t))436    def __binary_op(self, t, symbol):437        # Check if parenthesis are needed on left side and then dispatch438        has_paren = False439        left_class = str(t.left.__class__)440        if (left_class in op_precedence.keys() and441            op_precedence[left_class] < op_precedence[str(t.__class__)]):442            has_paren = True443        if has_paren:444            self._write('(')445        self._dispatch(t.left)446        if has_paren:447            self._write(')')448        # Write the appropriate symbol for operator449        self._write(symbol)450        # Check if parenthesis are needed on the right side and then dispatch451        has_paren = False452        right_class = str(t.right.__class__)453        if (right_class in op_precedence.keys() and454            op_precedence[right_class] < op_precedence[str(t.__class__)]):455            has_paren = True456        if has_paren:457            self._write('(')458        self._dispatch(t.right)459        if has_paren:460            self._write(')')461    def _float(self, t):462        # if t is 0.1, str(t)->'0.1' while repr(t)->'0.1000000000001'463        # We prefer str here.464        self._write(str(t))465    def _str(self, t):466        self._write(repr(t))467        468    def _tuple(self, t):469        self._write(str(t))470    #########################################################################471    # These are the methods from the _ast modules unparse.472    #473    # As our needs to handle more advanced code increase, we may want to474    # modify some of the methods below so that they work for compiler.ast.475    #########################################################################476#    # stmt477#    def _Expr(self, tree):478#        self._fill()479#        self._dispatch(tree.value)480#481#    def _Import(self, t):482#        self._fill("import ")483#        first = True484#        for a in t.names:485#            if first:486#                first = False487#            else:488#                self._write(", ")489#            self._write(a.name)490#            if a.asname:491#                self._write(" as "+a.asname)492#493##    def _ImportFrom(self, t):494##        self._fill("from ")495##        self._write(t.module)496##        self._write(" import ")497##        for i, a in enumerate(t.names):498##            if i == 0:499##                self._write(", ")500##            self._write(a.name)501##            if a.asname:502##                self._write(" as "+a.asname)503##        # XXX(jpe) what is level for?504##505#506#    def _Break(self, t):507#        self._fill("break")508#509#    def _Continue(self, t):510#        self._fill("continue")511#512#    def _Delete(self, t):513#        self._fill("del ")514#        self._dispatch(t.targets)515#516#    def _Assert(self, t):517#        self._fill("assert ")518#        self._dispatch(t.test)519#        if t.msg:520#            self._write(", ")521#            self._dispatch(t.msg)522#523#    def _Exec(self, t):524#        self._fill("exec ")525#        self._dispatch(t.body)526#        if t.globals:527#            self._write(" in ")528#            self._dispatch(t.globals)529#        if t.locals:530#            self._write(", ")531#            self._dispatch(t.locals)532#533#    def _Print(self, t):534#        self._fill("print ")535#        do_comma = False536#        if t.dest:537#            self._write(">>")538#            self._dispatch(t.dest)539#            do_comma = True540#        for e in t.values:541#            if do_comma:self._write(", ")542#            else:do_comma=True543#            self._dispatch(e)544#        if not t.nl:545#            self._write(",")546#547#    def _Global(self, t):548#        self._fill("global")549#        for i, n in enumerate(t.names):550#            if i != 0:551#                self._write(",")552#            self._write(" " + n)553#554#    def _Yield(self, t):555#        self._fill("yield")556#        if t.value:557#            self._write(" (")558#            self._dispatch(t.value)559#            self._write(")")560#561#    def _Raise(self, t):562#        self._fill('raise ')563#        if t.type:564#            self._dispatch(t.type)565#        if t.inst:566#            self._write(", ")567#            self._dispatch(t.inst)568#        if t.tback:569#            self._write(", ")570#            self._dispatch(t.tback)571#572#573#    def _TryFinally(self, t):574#        self._fill("try")575#        self._enter()576#        self._dispatch(t.body)577#        self._leave()578#579#        self._fill("finally")580#        self._enter()581#        self._dispatch(t.finalbody)582#        self._leave()583#584#    def _excepthandler(self, t):585#        self._fill("except ")586#        if t.type:587#            self._dispatch(t.type)588#        if t.name:589#            self._write(", ")590#            self._dispatch(t.name)591#        self._enter()592#        self._dispatch(t.body)593#        self._leave()594#595#    def _ClassDef(self, t):596#        self._write("\n")597#        self._fill("class "+t.name)598#        if t.bases:599#            self._write("(")600#            for a in t.bases:601#                self._dispatch(a)602#                self._write(", ")603#            self._write(")")604#        self._enter()605#        self._dispatch(t.body)606#        self._leave()607#608#    def _FunctionDef(self, t):609#        self._write("\n")610#        for deco in t.decorators:611#            self._fill("@")612#            self._dispatch(deco)613#        self._fill("def "+t.name + "(")614#        self._dispatch(t.args)615#        self._write(")")616#        self._enter()617#        self._dispatch(t.body)618#        self._leave()619#620#    def _For(self, t):621#        self._fill("for ")622#        self._dispatch(t.target)623#        self._write(" in ")624#        self._dispatch(t.iter)625#        self._enter()626#        self._dispatch(t.body)627#        self._leave()628#        if t.orelse:629#            self._fill("else")630#            self._enter()631#            self._dispatch(t.orelse)632#            self._leave633#634#    def _While(self, t):635#        self._fill("while ")636#        self._dispatch(t.test)637#        self._enter()638#        self._dispatch(t.body)639#        self._leave()640#        if t.orelse:641#            self._fill("else")642#            self._enter()643#            self._dispatch(t.orelse)644#            self._leave645#646#    # expr647#    def _Str(self, tree):648#        self._write(repr(tree.s))649##650#    def _Repr(self, t):651#        self._write("`")652#        self._dispatch(t.value)653#        self._write("`")654#655#    def _Num(self, t):656#        self._write(repr(t.n))657#658#    def _ListComp(self, t):659#        self._write("[")660#        self._dispatch(t.elt)661#        for gen in t.generators:662#            self._dispatch(gen)663#        self._write("]")664#665#    def _GeneratorExp(self, t):666#        self._write("(")667#        self._dispatch(t.elt)668#        for gen in t.generators:669#            self._dispatch(gen)670#        self._write(")")671#672#    def _comprehension(self, t):673#        self._write(" for ")674#        self._dispatch(t.target)675#        self._write(" in ")676#        self._dispatch(t.iter)677#        for if_clause in t.ifs:678#            self._write(" if ")679#            self._dispatch(if_clause)680#681#    def _IfExp(self, t):682#        self._dispatch(t.body)683#        self._write(" if ")684#        self._dispatch(t.test)685#        if t.orelse:686#            self._write(" else ")687#            self._dispatch(t.orelse)688#689#    unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"}690#    def _UnaryOp(self, t):691#        self._write(self.unop[t.op.__class__.__name__])692#        self._write("(")693#        self._dispatch(t.operand)694#        self._write(")")695#696#    binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%",697#                    "LShift":">>", "RShift":"<<", "BitOr":"|", "BitXor":"^", "BitAnd":"&",698#                    "FloorDiv":"//", "Pow": "**"}699#    def _BinOp(self, t):700#        self._write("(")701#        self._dispatch(t.left)702#        self._write(")" + self.binop[t.op.__class__.__name__] + "(")703#        self._dispatch(t.right)704#        self._write(")")705#706#    boolops = {_ast.And: 'and', _ast.Or: 'or'}707#    def _BoolOp(self, t):708#        self._write("(")709#        self._dispatch(t.values[0])710#        for v in t.values[1:]:711#            self._write(" %s " % self.boolops[t.op.__class__])712#            self._dispatch(v)713#        self._write(")")714#715#    def _Attribute(self,t):716#        self._dispatch(t.value)717#        self._write(".")718#        self._write(t.attr)719#720##    def _Call(self, t):721##        self._dispatch(t.func)722##        self._write("(")723##        comma = False724##        for e in t.args:725##            if comma: self._write(", ")726##            else: comma = True727##            self._dispatch(e)728##        for e in t.keywords:729##            if comma: self._write(", ")730##            else: comma = True731##            self._dispatch(e)732##        if t.starargs:733##            if comma: self._write(", ")734##            else: comma = True735##            self._write("*")736##            self._dispatch(t.starargs)737##        if t.kwargs:738##            if comma: self._write(", ")739##            else: comma = True740##            self._write("**")741##            self._dispatch(t.kwargs)742##        self._write(")")743#744#    # slice745#    def _Index(self, t):746#        self._dispatch(t.value)747#748#    def _ExtSlice(self, t):749#        for i, d in enumerate(t.dims):750#            if i != 0:751#                self._write(': ')752#            self._dispatch(d)753#754#    # others755#    def _arguments(self, t):756#        first = True757#        nonDef = len(t.args)-len(t.defaults)758#        for a in t.args[0:nonDef]:759#            if first:first = False760#            else: self._write(", ")761#            self._dispatch(a)762#        for a,d in zip(t.args[nonDef:], t.defaults):763#            if first:first = False764#            else: self._write(", ")765#            self._dispatch(a),766#            self._write("=")767#            self._dispatch(d)768#        if t.vararg:769#            if first:first = False770#            else: self._write(", ")771#            self._write("*"+t.vararg)772#        if t.kwarg:773#            if first:first = False774#            else: self._write(", ")775#            self._write("**"+t.kwarg)776#777##    def _keyword(self, t):778##        self._write(t.arg)779##        self._write("=")780##        self._dispatch(t.value)781#782#    def _Lambda(self, t):783#        self._write("lambda ")784#        self._dispatch(t.args)785#        self._write(": ")...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Blob._write('test.txt', 'test', 'utf8');2Cypress.Blob._write('test.txt', 'test', 'utf8');3Cypress.Blob._write('test.txt', 'test', 'utf8');4Cypress.Blob._write('test.txt', 'test', 'utf8');5Cypress.Blob._write('test.txt', 'test', 'utf8');6Cypress.Blob._write('test.txt', 'test', 'utf8');7Cypress.Blob._write('test.txt', 'test', 'utf8');8Cypress.Blob._write('test.txt', 'test', 'utf8');9Cypress.Blob._write('test.txt', 'test', 'utf8');10Cypress.Blob._write('test.txt', 'test', 'utf8');11Cypress.Blob._write('test.txt', 'test', 'utf8');12Cypress.Blob._write('test.txt', 'test', 'utf8');13Cypress.Blob._write('test.txt', 'test', 'utf8');14Cypress.Blob._write('test.txt', 'test', 'utf8');15Cypress.Blob._write('

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.log({2  consoleProps: () => {3    return {4    };5  },6  _write: (txt) => {7    console.log("test");8  }9});10Cypress.log({11  consoleProps: () => {12    return {13    };14  },15  _write: (txt) => {16    console.log("test");17  }18});19Cypress.log({20  consoleProps: () => {21    return {22    };23  },24  _write: (txt) => {25    console.log("test");26  }27});28Cypress.Commands.add('test', (txt) => {29  Cypress.log({30    consoleProps: () => {31      return {32      }33    },34    _write: (txt) => {35      console.log('test')36    }37  })38})39Cypress.Commands.add('test', (txt) => {40  Cypress.log({41    consoleProps: () => {42      return {43      }44    },45    _write: (txt) => {46      console.log('test')47    }48  })49})

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.log({2  consoleProps: () => {3    return {4    };5  },6  _write: (message) => {7    console.log(message);8  },9});

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.get('input').write('hello world')2Cypress.Commands.add('write', { prevSubject: 'element' }, (subject, text) => {3  cy.wrap(subject).type(text)4})5Cypress.Commands.add('write', { prevSubject: 'element' }, (subject, text) => {6  cy.wrap(subject).type(text)7})8declare namespace Cypress {9  interface Chainable {10    write(text: string): Chainable<Element>11  }12}13declare namespace Cypress {14  interface Chainable {15    write(text: string): Chainable<Element>16  }17}18declare namespace Cypress {19  interface Chainable {20    write(text: string): Chainable<Element>21  }22}23declare namespace Cypress {24  interface Chainable {25    write(text: string): Chainable<Element>26  }27}28declare namespace Cypress {29  interface Chainable {30    write(text: string): Chainable<Element>31  }32}33declare namespace Cypress {34  interface Chainable {35    write(text: string): Chainable<Element>36  }37}38declare namespace Cypress {39  interface Chainable {40    write(text: string): Chainable<Element>41  }42}43declare namespace Cypress {44  interface Chainable {45    write(text: string): Chainable<Element>46  }47}48declare namespace Cypress {49  interface Chainable {50    write(text: string): Chainable<Element>51  }52}53declare namespace Cypress {54  interface Chainable {55    write(text:

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.writeFile('path/to/file.txt', 'Hello, World!', 'utf8')2cy.writeFile('path/to/file.txt', 'Hello, World!', { encoding: 'utf8' })3const fs = require('fs')4fs.writeFileSync('path/to/file.txt', 'Hello, World!', 'utf8')5fs.writeFileSync('path/to/file.txt', 'Hello, World!', { encoding: 'utf8' })6const fs = require('fs')7fs.writeFileSync('path/to/file.txt', 'Hello, World!', 'utf8')8fs.writeFileSync('path/to/file.txt', 'Hello, World!', { encoding: 'utf8' })9const fs = require('fs')10fs.writeFileSync('path/to/file.txt', 'Hello, World!', 'utf8')11fs.writeFileSync('path/to/file.txt', 'Hello, World!', { encoding: 'utf8' })12const fs = require('fs')13fs.writeFileSync('path/to/file.txt', 'Hello, World!', 'utf8')14fs.writeFileSync('path/to/file.txt', 'Hello, World!', { encoding: 'utf8' })15const fs = require('fs')16fs.writeFileSync('path/to/file.txt', 'Hello, World!', 'utf8')17fs.writeFileSync('path/to/file.txt', 'Hello, World!', { encoding: 'utf8' })18const fs = require('fs')19fs.writeFileSync('path/to/file.txt', 'Hello, World!', 'utf8')20fs.writeFileSync('path/to/file.txt', 'Hello, World!', { encoding: 'utf8' })21const fs = require('fs')22fs.writeFileSync('path/to/file.txt', 'Hello, World!', 'utf8')23fs.writeFileSync('path/to/file.txt', 'Hello, World!', { encoding: 'utf8' })24const fs = require('fs')25fs.writeFileSync('path/to/file.txt', 'Hello, World!', 'utf8')26fs.writeFileSync('path/to/file.txt', 'Hello, World

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.log({2  consoleProps: () => {3    return {4    }5  }6})7Cypress.Commands.add('customLog', (message) => {8  Cypress.log({9    consoleProps: () => {10      return {11      }12    }13  })14})15cy.customLog('This is a custom log')

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