How to use extend method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

extend-visitor.js

Source: extend-visitor.js Github

copy
1(function (tree) {
2    /*jshint loopfunc:true */
3
4    tree.extendFinderVisitor = function() {
5        this._visitor = new tree.visitor(this);
6        this.contexts = [];
7        this.allExtendsStack = [[]];
8    };
9
10    tree.extendFinderVisitor.prototype = {
11        run: function (root) {
12            root = this._visitor.visit(root);
13            root.allExtends = this.allExtendsStack[0];
14            return root;
15        },
16        visitRule: function (ruleNode, visitArgs) {
17            visitArgs.visitDeeper = false;
18        },
19        visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
20            visitArgs.visitDeeper = false;
21        },
22        visitRuleset: function (rulesetNode, visitArgs) {
23            if (rulesetNode.root) {
24                return;
25            }
26
27            var i, j, extend, allSelectorsExtendList = [], extendList;
28
29            // get &:extend(.a); rules which apply to all selectors in this ruleset
30            var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0;
31            for(i = 0; i < ruleCnt; i++) {
32                if (rulesetNode.rules[i] instanceof tree.Extend) {
33                    allSelectorsExtendList.push(rules[i]);
34                    rulesetNode.extendOnEveryPath = true;
35                }
36            }
37
38            // now find every selector and apply the extends that apply to all extends
39            // and the ones which apply to an individual extend
40            var paths = rulesetNode.paths;
41            for(i = 0; i < paths.length; i++) {
42                var selectorPath = paths[i],
43                    selector = selectorPath[selectorPath.length - 1],
44                    selExtendList = selector.extendList;
45
46                extendList = selExtendList ? selExtendList.slice(0).concat(allSelectorsExtendList)
47                                           : allSelectorsExtendList;
48
49                if (extendList) {
50                    extendList = extendList.map(function(allSelectorsExtend) {
51                        return allSelectorsExtend.clone();
52                    });
53                }
54
55                for(j = 0; j < extendList.length; j++) {
56                    this.foundExtends = true;
57                    extend = extendList[j];
58                    extend.findSelfSelectors(selectorPath);
59                    extend.ruleset = rulesetNode;
60                    if (j === 0) { extend.firstExtendOnThisSelectorPath = true; }
61                    this.allExtendsStack[this.allExtendsStack.length-1].push(extend);
62                }
63            }
64
65            this.contexts.push(rulesetNode.selectors);
66        },
67        visitRulesetOut: function (rulesetNode) {
68            if (!rulesetNode.root) {
69                this.contexts.length = this.contexts.length - 1;
70            }
71        },
72        visitMedia: function (mediaNode, visitArgs) {
73            mediaNode.allExtends = [];
74            this.allExtendsStack.push(mediaNode.allExtends);
75        },
76        visitMediaOut: function (mediaNode) {
77            this.allExtendsStack.length = this.allExtendsStack.length - 1;
78        },
79        visitDirective: function (directiveNode, visitArgs) {
80            directiveNode.allExtends = [];
81            this.allExtendsStack.push(directiveNode.allExtends);
82        },
83        visitDirectiveOut: function (directiveNode) {
84            this.allExtendsStack.length = this.allExtendsStack.length - 1;
85        }
86    };
87
88    tree.processExtendsVisitor = function() {
89        this._visitor = new tree.visitor(this);
90    };
91
92    tree.processExtendsVisitor.prototype = {
93        run: function(root) {
94            var extendFinder = new tree.extendFinderVisitor();
95            extendFinder.run(root);
96            if (!extendFinder.foundExtends) { return root; }
97            root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
98            this.allExtendsStack = [root.allExtends];
99            return this._visitor.visit(root);
100        },
101        doExtendChaining: function (extendsList, extendsListTarget, iterationCount) {
102            //
103            // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering and pasting
104            // the selector we would do normally, but we are also adding an extend with the same target selector
105            // this means this new extend can then go and alter other extends
106            //
107            // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
108            // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already processed if
109            // we look at each selector at a time, as is done in visitRuleset
110
111            var extendIndex, targetExtendIndex, matches, extendsToAdd = [], newSelector, extendVisitor = this, selectorPath, extend, targetExtend, newExtend;
112
113            iterationCount = iterationCount || 0;
114
115            //loop through comparing every extend with every target extend.
116            // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
117            // e.g.  .a:extend(.b) {}  and .b:extend(.c) {} then the first extend extends the second one
118            // and the second is the target.
119            // the seperation into two lists allows us to process a subset of chains with a bigger set, as is the
120            // case when processing media queries
121            for(extendIndex = 0; extendIndex < extendsList.length; extendIndex++){
122                for(targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++){
123
124                    extend = extendsList[extendIndex];
125                    targetExtend = extendsListTarget[targetExtendIndex];
126
127                    // look for circular references
128                    if( extend.parent_ids.indexOf( targetExtend.object_id ) >= 0 ){ continue; }
129
130                    // find a match in the target extends self selector (the bit before :extend)
131                    selectorPath = [targetExtend.selfSelectors[0]];
132                    matches = extendVisitor.findMatch(extend, selectorPath);
133
134                    if (matches.length) {
135
136                        // we found a match, so for each self selector..
137                        extend.selfSelectors.forEach(function(selfSelector) {
138
139                            // process the extend as usual
140                            newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector);
141
142                            // but now we create a new extend from it
143                            newExtend = new(tree.Extend)(targetExtend.selector, targetExtend.option, 0);
144                            newExtend.selfSelectors = newSelector;
145
146                            // add the extend onto the list of extends for that selector
147                            newSelector[newSelector.length-1].extendList = [newExtend];
148
149                            // record that we need to add it.
150                            extendsToAdd.push(newExtend);
151                            newExtend.ruleset = targetExtend.ruleset;
152
153                            //remember its parents for circular references
154                            newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids);
155
156                            // only process the selector once.. if we have :extend(.a,.b) then multiple
157                            // extends will look at the same selector path, so when extending
158                            // we know that any others will be duplicates in terms of what is added to the css
159                            if (targetExtend.firstExtendOnThisSelectorPath) {
160                                newExtend.firstExtendOnThisSelectorPath = true;
161                                targetExtend.ruleset.paths.push(newSelector);
162                            }
163                        });
164                    }
165                }
166            }
167
168            if (extendsToAdd.length) {
169                // try to detect circular references to stop a stack overflow.
170                // may no longer be needed.
171                this.extendChainCount++;
172                if (iterationCount > 100) {
173                    var selectorOne = "{unable to calculate}";
174                    var selectorTwo = "{unable to calculate}";
175                    try
176                    {
177                        selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
178                        selectorTwo = extendsToAdd[0].selector.toCSS();
179                    }
180                    catch(e) {}
181                    throw {message: "extend circular reference detected. One of the circular extends is currently:"+selectorOne+":extend(" + selectorTwo+")"};
182                }
183
184                // now process the new extends on the existing rules so that we can handle a extending b extending c ectending d extending e...
185                return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount+1));
186            } else {
187                return extendsToAdd;
188            }
189        },
190        visitRule: function (ruleNode, visitArgs) {
191            visitArgs.visitDeeper = false;
192        },
193        visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
194            visitArgs.visitDeeper = false;
195        },
196        visitSelector: function (selectorNode, visitArgs) {
197            visitArgs.visitDeeper = false;
198        },
199        visitRuleset: function (rulesetNode, visitArgs) {
200            if (rulesetNode.root) {
201                return;
202            }
203            var matches, pathIndex, extendIndex, allExtends = this.allExtendsStack[this.allExtendsStack.length-1], selectorsToAdd = [], extendVisitor = this, selectorPath;
204
205            // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
206
207            for(extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
208                for(pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
209                    selectorPath = rulesetNode.paths[pathIndex];
210
211                    // extending extends happens initially, before the main pass
212                    if (rulesetNode.extendOnEveryPath) { continue; }
213                    var extendList = selectorPath[selectorPath.length-1].extendList;
214                    if (extendList && extendList.length) { continue; }
215
216                    matches = this.findMatch(allExtends[extendIndex], selectorPath);
217
218                    if (matches.length) {
219
220                        allExtends[extendIndex].selfSelectors.forEach(function(selfSelector) {
221                            selectorsToAdd.push(extendVisitor.extendSelector(matches, selectorPath, selfSelector));
222                        });
223                    }
224                }
225            }
226            rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
227        },
228        findMatch: function (extend, haystackSelectorPath) {
229            //
230            // look through the haystack selector path to try and find the needle - extend.selector
231            // returns an array of selector matches that can then be replaced
232            //
233            var haystackSelectorIndex, hackstackSelector, hackstackElementIndex, haystackElement,
234                targetCombinator, i,
235                extendVisitor = this,
236                needleElements = extend.selector.elements,
237                potentialMatches = [], potentialMatch, matches = [];
238
239            // loop through the haystack elements
240            for(haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
241                hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
242
243                for(hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
244
245                    haystackElement = hackstackSelector.elements[hackstackElementIndex];
246
247                    // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
248                    if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
249                        potentialMatches.push({pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0, initialCombinator: haystackElement.combinator});
250                    }
251
252                    for(i = 0; i < potentialMatches.length; i++) {
253                        potentialMatch = potentialMatches[i];
254
255                        // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
256                        // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out
257                        // what the resulting combinator will be
258                        targetCombinator = haystackElement.combinator.value;
259                        if (targetCombinator === '' && hackstackElementIndex === 0) {
260                            targetCombinator = ' ';
261                        }
262
263                        // if we don't match, null our match to indicate failure
264                        if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) ||
265                            (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) {
266                            potentialMatch = null;
267                        } else {
268                            potentialMatch.matched++;
269                        }
270
271                        // if we are still valid and have finished, test whether we have elements after and whether these are allowed
272                        if (potentialMatch) {
273                            potentialMatch.finished = potentialMatch.matched === needleElements.length;
274                            if (potentialMatch.finished &&
275                                (!extend.allowAfter && (hackstackElementIndex+1 < hackstackSelector.elements.length || haystackSelectorIndex+1 < haystackSelectorPath.length))) {
276                                potentialMatch = null;
277                            }
278                        }
279                        // if null we remove, if not, we are still valid, so either push as a valid match or continue
280                        if (potentialMatch) {
281                            if (potentialMatch.finished) {
282                                potentialMatch.length = needleElements.length;
283                                potentialMatch.endPathIndex = haystackSelectorIndex;
284                                potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
285                                potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
286                                matches.push(potentialMatch);
287                            }
288                        } else {
289                            potentialMatches.splice(i, 1);
290                            i--;
291                        }
292                    }
293                }
294            }
295            return matches;
296        },
297        isElementValuesEqual: function(elementValue1, elementValue2) {
298            if (typeof elementValue1 === "string" || typeof elementValue2 === "string") {
299                return elementValue1 === elementValue2;
300            }
301            if (elementValue1 instanceof tree.Attribute) {
302                if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
303                    return false;
304                }
305                if (!elementValue1.value || !elementValue2.value) {
306                    if (elementValue1.value || elementValue2.value) {
307                        return false;
308                    }
309                    return true;
310                }
311                elementValue1 = elementValue1.value.value || elementValue1.value;
312                elementValue2 = elementValue2.value.value || elementValue2.value;
313                return elementValue1 === elementValue2;
314            }
315            elementValue1 = elementValue1.value;
316            elementValue2 = elementValue2.value;
317            if (elementValue1 instanceof tree.Selector) {
318                if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
319                    return false;
320                }
321                for(var i = 0; i <elementValue1.elements.length; i++) {
322                    if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
323                        if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
324                            return false;
325                        }
326                    }
327                    if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
328                        return false;
329                    }
330                }
331                return true;
332            }
333            return false;
334        },
335        extendSelector:function (matches, selectorPath, replacementSelector) {
336
337            //for a set of matches, replace each match with the replacement selector
338
339            var currentSelectorPathIndex = 0,
340                currentSelectorPathElementIndex = 0,
341                path = [],
342                matchIndex,
343                selector,
344                firstElement,
345                match,
346                newElements;
347
348            for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
349                match = matches[matchIndex];
350                selector = selectorPath[match.pathIndex];
351                firstElement = new tree.Element(
352                    match.initialCombinator,
353                    replacementSelector.elements[0].value,
354                    replacementSelector.elements[0].index,
355                    replacementSelector.elements[0].currentFileInfo
356                );
357
358                if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
359                    path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
360                    currentSelectorPathElementIndex = 0;
361                    currentSelectorPathIndex++;
362                }
363
364                newElements = selector.elements
365                    .slice(currentSelectorPathElementIndex, match.index)
366                    .concat([firstElement])
367                    .concat(replacementSelector.elements.slice(1));
368
369                if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
370                    path[path.length - 1].elements =
371                        path[path.length - 1].elements.concat(newElements);
372                } else {
373                    path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
374
375                    path.push(new tree.Selector(
376                        newElements
377                    ));
378                }
379                currentSelectorPathIndex = match.endPathIndex;
380                currentSelectorPathElementIndex = match.endPathElementIndex;
381                if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
382                    currentSelectorPathElementIndex = 0;
383                    currentSelectorPathIndex++;
384                }
385            }
386
387            if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
388                path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
389                currentSelectorPathIndex++;
390            }
391
392            path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
393
394            return path;
395        },
396        visitRulesetOut: function (rulesetNode) {
397        },
398        visitMedia: function (mediaNode, visitArgs) {
399            var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]);
400            newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
401            this.allExtendsStack.push(newAllExtends);
402        },
403        visitMediaOut: function (mediaNode) {
404            this.allExtendsStack.length = this.allExtendsStack.length - 1;
405        },
406        visitDirective: function (directiveNode, visitArgs) {
407            var newAllExtends = directiveNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]);
408            newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, directiveNode.allExtends));
409            this.allExtendsStack.push(newAllExtends);
410        },
411        visitDirectiveOut: function (directiveNode) {
412            this.allExtendsStack.length = this.allExtendsStack.length - 1;
413        }
414    };
415
416})(require('./tree'));
417
Full Screen

es5-visitors.js

Source: es5-visitors.js Github

copy
1var es5_visitors = (function () {
2
3    var types = require("babel-types"),
4
5        defaultExtendDecoratorName = "JavaProxy",
6        columnOffset = 1,
7        ASTERISK_SEPARATOR = "*",
8        customExtendsArr = [],
9        normalExtendsArr = [],
10        interfacesArr = [],
11        UNSUPPORTED_TYPESCRIPT_EXTEND_FORMAT_MESSAGE = "[WARN] TypeScript-extended class has a super() call in an unsupported format.",
12
13        customExtendsArrGlobal = [];
14
15	/* 	ENTRY POINT!
16	*	Traverses each passed node with several visitors.
17	*	Result from visit can be got from static methods.
18	*
19	*	Input parameters: 
20	*		path - node to visit
21	*		config - filename, decorator name ...
22	*/
23    function es5Visitor(path, config) {
24
25        if (!config.filePath) {
26            config.filePath = "No file path provided";
27        }
28
29        if (path.node.skipMeOnVisit) {
30            return;
31        }
32
33        // ES5 Syntax
34        // anchor is extend (normal extend pattern + custom extend pattern) 
35        if (types.isMemberExpression(path) && path.node.property.name === "extend") {
36            traverseEs5Extend(path, config);
37        }
38
39        //anchor is new keyword (interface pattern)
40        if (types.isNewExpression(path)) {
41            traverseInterface(path, config);
42        }
43
44        // // Parsed Typescript to ES5 Syntax (normal extend pattern + custom extend pattern)
45        // 	// anchor is __extends
46        if (types.isIdentifier(path) && path.node.name === "__extends") {
47            traverseTsExtend(path, config);
48        }
49        // Maybe it's not a good idea to expose this scenario because it can be explicitly covered
50        // //anchor is JavaProxy (optional)
51        // var customDecoratorName = config.extendDecoratorName === undefined ? defaultExtendDecoratorName : config.extendDecoratorName;
52        // if(t.isIdentifier(path) && path.node.name === customDecoratorName) {
53        // if(path.node.skipMeOnVisit) {
54        // 	return;
55        // }
56        // console.log("enters because there is a java proxy down the way")
57        // traverseJavaProxyExtend(path, config, customDecoratorName);
58        // }
59
60    }
61
62	/*
63	*	Returns the custom extends array generated from visitor
64	*/
65    es5Visitor.getProxyExtendInfo = function () {
66        var res = customExtendsArr.slice();
67        customExtendsArr = [];
68        return res;
69    }
70
71    /*
72   *       Returns the common extends array generated from visitor
73   */
74    es5Visitor.getCommonExtendInfo = function () {
75        var res = [];
76        for (var index in normalExtendsArr) {
77            if (normalExtendsArr[index][0] !== "*") {
78                res.push(normalExtendsArr[index]);
79            }
80        }
81
82        normalExtendsArr = [];
83        return res;
84    }
85
86	/*
87	*	Returns the extended interfaces array generated from visitor
88	*/
89    es5Visitor.getInterfaceInfo = function () {
90        var res = interfacesArr.slice();
91        interfacesArr = [];
92        return res;
93    }
94
95	/* 
96	*	Traverses the typescript extend case (__extends())
97	*	Write results in "normalExtendsArr" or "customExtendsArr".
98	*/
99    function traverseTsExtend(path, config) {
100        // information for normal extend (unnamed)
101        var extendClass;
102        try {
103            extendClass = _getArgumentFromNodeAsString(path, 5, config)
104        } catch (e) {
105            config.logger.info(e.message)
106            return;
107        }
108
109        var overriddenMethodNames = _getOverriddenMethodsTypescript(path, 3);
110
111        var extendPath = _getParent(path, 3, config);
112        var declaredClassName = "";
113
114        var typescriptClassExtendSuperCallLocation = getTypeScriptExtendSuperCallLocation(extendPath, config);
115        var extendParent = _getParent(path, 1, config);
116
117        if (types.isCallExpression(extendParent)) {
118            declaredClassName = extendParent.node.arguments[0].name;
119        }
120
121        var decorateNodes = traverseForDecorate(path, config, 3);
122
123        var isDecoratedWithExtend = false,
124            customExtendDecoratorName,
125            customExtendDecoratorValue,
126            implementedInterfaces = [];
127
128        if (!decorateNodes) {
129            // 7 -> Takes 7 levels up to get to the scope where the class is declared
130            decorateNodes = traverseForDecorateSpecial(path, config, 7);
131        }
132
133        if (decorateNodes) {
134            for (var i in decorateNodes) {
135                var currentDecorator = decorateNodes[i];
136                if (types.isCallExpression(currentDecorator)) {
137                    // Interfaces/Implements
138                    if (currentDecorator.callee.name === config.interfacesDecoratorName) {
139                        currentDecorator.callee.skipMeOnVisit = true;
140
141                        var interfaces = currentDecorator.arguments[0].elements;
142
143                        for (var i in interfaces) {
144                            var interfaceName = _getWholeInterfaceNameFromInterfacesNode(interfaces[i]);
145                            implementedInterfaces.push(interfaceName);
146                        }
147                    }
148
149                    // JavaProxy
150                    if (currentDecorator.callee.name === config.extendDecoratorName) {
151                        currentDecorator.callee.skipMeOnVisit = true;
152
153                        isDecoratedWithExtend = true;
154
155                        customExtendDecoratorName = config.extendDecoratorName === undefined ? defaultExtendDecoratorName : config.extendDecoratorName;
156                        customExtendDecoratorValue = currentDecorator.arguments[0].value;
157                    }
158                }
159            }
160        }
161
162        if (isDecoratedWithExtend) {
163            traverseJavaProxyExtend(customExtendDecoratorValue, config, customExtendDecoratorName, extendClass, overriddenMethodNames, implementedInterfaces);
164        } else {
165            var lineToWrite;
166
167            lineToWrite = _generateLineToWrite("", extendClass, overriddenMethodNames, { file: config.filePath, line: typescriptClassExtendSuperCallLocation.line, column: typescriptClassExtendSuperCallLocation.column, className: declaredClassName }, "", implementedInterfaces);
168
169            if (config.logger) {
170                config.logger.info(lineToWrite)
171            }
172
173            normalExtendsArr.push(lineToWrite);
174        }
175    }
176
177    function getTypeScriptExtendSuperCallLocation(extendPath, config) {
178        var constructorFunctionName;
179        var returnIdentifierName;
180        var superCalleeStartColumn;
181        var superCalleeLine;
182        var locationAssigned = false;
183
184        // checks if constructor function and return identifiers match in a transpiled typescript class extend
185        if (extendPath.node.body && extendPath.node.body.length >= 3) {
186            if (types.isFunctionDeclaration(extendPath.node.body[1]) && extendPath.node.body[1].id)
187                constructorFunctionName = extendPath.node.body[1].id.name;
188            if (types.isReturnStatement(extendPath.node.body[extendPath.node.body.length - 1]))
189                returnIdentifierName = extendPath.node.body[extendPath.node.body.length - 1].argument.name;
190        }
191
192        // checks the typescript-extended class for a strict format, and a super call/apply inside
193        /**
194         *      function MyBtn() {
195                    var _this = _super.call(this) || this;
196                    return global.__native(_this);
197                }
198
199                **UGLIFIED extended class**
200
201                function t(t) {
202                    var r = e.call(this) || this;
203                    r.textBase = t;
204                    return global.__native(r);
205                }
206         */
207        if (constructorFunctionName === returnIdentifierName && !!constructorFunctionName) {
208            var constructorFunctionScope = extendPath.node.body[1];
209            // the 'super' variable will always be passed as the second argument to the __extends call
210            // try to find the 'super' identifier which may be uglified
211            var superVariableIdentifier = getSuperVariableIdentifier(extendPath.node.body[0]);
212
213            //// helper functions to find the correct super.call(this) node
214            function getSuperVariableIdentifier(__extendsNode) {
215                if (types.isExpressionStatement(__extendsNode) && types.isCallExpression(__extendsNode.expression)) {
216                    var __extendsCallArguments = __extendsNode.expression.arguments;
217                    if (__extendsCallArguments.length == 2) {
218                        return __extendsCallArguments[1].name;
219                    }
220                }
221            }
222
223            /** Getting the super.call node from assignment
224                if expressionStatement => check possibleExpressionStatements[0]
225                if possibleExpressionStatements[0].expression is assignment expression
226                if possibleExpressionStatements[0].expression.right is logical expression
227                if possibleExpressionStatements[0].expression.right.left is Call expression
228                if possibleExpressionStatements[0].expression.right.left.callee.object.name === superVariableIdentifier
229                if the above is valid, then variableRHS = possibleVariableDeclarations[0].expression.right.left 
230             */
231            function getThisAssignmentSuperCallLineNode(nodes, superIdentifier) {
232                var matchingNodes = nodes.filter(
233                    (node) => {
234                        return types.isAssignmentExpression(node.expression)
235                            && types.isLogicalExpression(node.expression.right)
236                            && types.isCallExpression(node.expression.right.left)
237                            && node.expression.right.left.callee.object.name === superIdentifier;
238                    });
239
240                return matchingNodes.length > 0 ? matchingNodes[0].expression.right.left : null;
241            }
242
243            /** Getting the super.call node from declaration
244                if variableDeclaration => check possibleVariableDeclarations[0].declarations[0].init  isn't null
245                if possibleNodesForSuperCall[0].declarations[0].init is logical expression
246                if possibleNodesForSuperCall[0].declarations[0].init.left is Call Expression
247                if possibleNodesForSuperCall[0].declarations[0].init.left.callee.object.name === superVariableIdentifier
248                if the above is valid, then variableRHS = possibleVariableDeclarations[0].declarations[0].init.left
249             */
250            function getThisDeclarationSuperCallLineNode(nodes, superIdentifier) {
251                var matchingNodes = nodes.filter(
252                    (node) => {
253                        return types.isLogicalExpression(node.declarations[0].init)
254                            && types.isCallExpression(node.declarations[0].init.left)
255                            && node.declarations[0].init.left.callee.object.name === superIdentifier;
256                    });
257
258                return matchingNodes.length > 0 ? matchingNodes[0].declarations[0].init.left : null;
259            }
260            ////
261
262            if (superVariableIdentifier) {
263                var possibleVariableDeclarations = [];
264                var possibleExpressionStatements = [];
265
266                constructorFunctionScope.body.body.forEach(node => {
267                    if (types.isVariableDeclaration(node)) {
268                        possibleVariableDeclarations.push(node);
269                    } else if (types.isExpressionStatement(node)) {
270                        possibleExpressionStatements.push(node);
271                    }
272                });
273
274                if (possibleVariableDeclarations.length > 0 || possibleExpressionStatements.length > 0) {
275                    var superCallRHS = getThisDeclarationSuperCallLineNode(possibleVariableDeclarations, superVariableIdentifier)
276                        || getThisAssignmentSuperCallLineNode(possibleExpressionStatements, superVariableIdentifier);
277
278                    if (superCallRHS) {
279                        var superCallee = superCallRHS.callee.property;
280                        superCalleeStartColumn = superCallee.loc.start.column + 1;
281                        superCalleeLine = superCallee.loc.start.line;
282
283                        locationAssigned = true;
284                    }
285                }
286            }
287        }
288
289        if (!locationAssigned) {
290            config.logger.info(UNSUPPORTED_TYPESCRIPT_EXTEND_FORMAT_MESSAGE + " ctor function name: " + constructorFunctionName);
291        }
292
293        return {
294            line: superCalleeLine,
295            column: superCalleeStartColumn
296        };
297    }
298
299    function traverseForDecorate(path, config, depth) {
300        var iifeRoot = _getParent(path, depth)
301        var body = iifeRoot.node.body;
302        for (var index in body) {
303            var ci = body[index];
304            if (isDecorateStatement(ci)) {
305                // returns the node of the decorate (node.expression.right.callee)
306                // __decorate([..])
307                return ci.expression.right.arguments[0].elements;
308            }
309        }
310
311        return null;
312    }
313
314    function traverseForDecorateSpecial(path, config, depth) {
315        var iifeRoot = _getParent(path, depth);
316
317        var sibling = iifeRoot.getSibling(iifeRoot.key + 1).node;
318        if (sibling) {
319            if (isDecorateStatement(sibling)) {
320                // returns the node of the decorate (node.expression.right.callee)
321                // __decorate([..])
322                return sibling.expression.right.arguments[0].elements;
323            }
324        }
325
326        return null;
327    }
328
329    function isDecorateStatement(node) {
330        return types.isExpressionStatement(node) &&
331            types.isAssignmentExpression(node.expression) &&
332            node.expression.right.callee &&
333            node.expression.right.callee.name === "__decorate" &&
334            node.expression.right.arguments &&
335            types.isArrayExpression(node.expression.right.arguments[0])
336    }
337
338	/* 
339	*	Traverses the node, which is a "new" expression and find if it's a native interface or not.
340	*	Write results in "interfacesArr".
341	*/
342    function traverseInterface(path, config) {
343        if (!config.interfaceNames) {
344            throw "No interface names are provided! You can pass them in config.interfaceNames as an array!"
345        }
346
347        var o = path.node.callee,
348            interfaceArr = _getWholeName(o),
349            foundInterface = false,
350            interfaceNames = config.interfaceNames
351
352        var currentInterface = interfaceArr.reverse().join(".");
353        for (var i in interfaceNames) {
354            var interfaceName = interfaceNames[i].trim();
355            if (interfaceName === currentInterface) {
356                currentInterface = interfaceName;
357                foundInterface = true;
358                break;
359            }
360        }
361
362        if (foundInterface) {
363            var arg0 = "",
364                arg1;
365            if (path.node.arguments.length === 1) {
366                arg1 = path.node.arguments[0];
367            }
368            else if (path.node.arguments.length === 2) {
369                arg0 = path.node.arguments[0];
370                arg1 = path.node.arguments[1];
371            }
372            else {
373                throw {
374                    message: "Not enough or too many arguments passed(" + path.node.arguments.length + ") when trying to extend interface in file: " + config.filePath,
375                    errCode: 1
376                }
377            }
378
379            var isCorrectInterfaceName = _testClassName(arg0.value);
380            var overriddenInterfaceMethods = _getOverriddenMethods(arg1, config);
381            var extendInfo = {
382                file: config.filePath,
383                line: path.node.loc.start.line,
384                column: path.node.loc.start.column + columnOffset,
385                className: (isCorrectInterfaceName ? arg0.value : "")
386            }
387            var lineToWrite = _generateLineToWrite("", currentInterface, overriddenInterfaceMethods.join(","), extendInfo, "");
388            if (config.logger) {
389                config.logger.info(lineToWrite)
390            }
391
392            interfacesArr.push(lineToWrite)
393        }
394    }
395
396	/* 
397	*	Finds the java proxy name from custom class decorator.
398	*	Write results in "customExtendsArr"
399	*/
400    function traverseJavaProxyExtend(path, config, customDecoratorName, extendClass, overriddenMethodNames, implementedInterfaces) {
401        if (config.logger) {
402            config.logger.info("\t+in " + customDecoratorName + " anchor");
403        }
404
405        var classNameFromDecorator = path;//_getDecoratorArgument(path, config, customDecoratorName);
406
407        var lineToWrite = _generateLineToWrite(classNameFromDecorator, extendClass, overriddenMethodNames, "", config.fullPathName, implementedInterfaces);
408        if (config.logger) {
409            config.logger.info(lineToWrite)
410        }
411        addCustomExtend(classNameFromDecorator, config.fullPathName, lineToWrite)
412    }
413
414	/* 
415	*	Finds the normal extend name, overridden methods and possibly java proxy name from passed node.
416	*	Writes to "customExtendsArr" or "normalExtendsArr".
417	*	Left whole for readability.
418	*/
419    function traverseEs5Extend(path, config) {
420        var callee = path.parent.callee;
421
422        if (callee) {
423            var o = callee.object
424            extendClass = _getWholeName(o);
425
426            var extendArguments = path.parent.arguments;
427            var arg0,
428                arg1;
429            if (extendArguments.length === 1 && types.isObjectExpression(arg0)) {
430                arg0 = extendArguments[0];
431            }
432            else if (types.isStringLiteral(arg0)) {
433
434            }
435
436            var arg0 = "",
437                arg1;
438            if (extendArguments.length) {
439                // Get implementation object when there is only 1 argument
440                if (extendArguments.length === 1 && types.isObjectExpression(extendArguments[0])) {
441                    arg1 = extendArguments[0];
442                }
443                // Get the name of the extended class and the implementation object when both arguments are present
444                else if (extendArguments.length === 2) {
445                    if (types.isStringLiteral(extendArguments[0]) && types.isObjectExpression(extendArguments[1])) {
446                        arg0 = extendArguments[0];
447                        arg1 = extendArguments[1];
448                    }
449                }
450                else {
451                    // don't throw here, because there can be a valid js extend that has nothing to do with NS
452                    return;
453                    throw {
454                        message: "Not enough or too many arguments passed(" + extendArguments.length + ") when trying to extend class in file: " + config.filePath,
455                        errCode: 1
456                    }
457                }
458            }
459            else {
460                // don't throw here, because there can be a valid js extend that has nothing to do with NS
461                return;
462                throw {
463                    message: "You need to call the extend with parameters. Example: '...extend(\"a.b.C\", {...overrides...})') in file: " + config.filePath,
464                    errCode: 1
465                }
466            }
467
468            className = arg0.value ? arg0.value : "";
469
470            // Get all methods from the implementation object
471            var methodsAndInterfaces = _getOverridenMethodsAndImplementedInterfaces(arg1, config);
472            var overriddenMethodNames = methodsAndInterfaces[0];
473            var implementedInterfaces = methodsAndInterfaces[1];
474
475            var isCorrectExtendClassName = _testJavaProxyName(className);
476            var isCorrectClassName = _testClassName(className);
477            if (className && !isCorrectClassName && !isCorrectExtendClassName) {
478                throw {
479                    message: "The 'extend' you are trying to make has an invalid name. Example: '...extend(\"a.b.C\", {...overrides...})'), file: " + config.filePath,
480                    errCode: 1
481                }
482            }
483
484            var lineToWrite = "";
485            if (isCorrectExtendClassName) {
486                if (config.logger) {
487                    config.logger.info(lineToWrite)
488                }
489
490                var classNameFromDecorator = isCorrectExtendClassName ? className : "";
491                lineToWrite = _generateLineToWrite(classNameFromDecorator, extendClass.reverse().join("."), overriddenMethodNames, "", config.fullPathName, implementedInterfaces);
492                addCustomExtend(classNameFromDecorator, config.fullPathName, lineToWrite);
493
494                return;
495            }
496
497            if (config.logger) {
498                config.logger.info(lineToWrite)
499            }
500            var extendInfo = {
501                file: config.filePath,
502                line: path.node.property.loc.start.line,
503                column: path.node.property.loc.start.column + columnOffset,
504                className: className
505            };
506            lineToWrite = _generateLineToWrite(isCorrectExtendClassName ? className : "", extendClass.reverse().join("."), overriddenMethodNames, extendInfo, "", implementedInterfaces);
507            normalExtendsArr.push(lineToWrite)
508        }
509        else {
510            // don't throw here, because there can be a valid js extend that has nothing to do with NS
511            return;
512            throw {
513                message: "You need to call the extend '...extend(\"extend_name\", {...overrides...})'), file: " + config.filePath,
514                errCode: 1
515            }
516        }
517    }
518
519	/* 
520	*	HELPER METHODS
521	*/
522    function _getOverriddenMethods(node, config) {
523        var overriddenMethodNames = [];
524        if (types.isObjectExpression(node)) {
525            var objectProperties = node.properties;
526
527            for (var index in objectProperties) {
528                overriddenMethodNames.push(objectProperties[index].key.name);
529            }
530        }
531
532        return overriddenMethodNames;
533    }
534
535    // NOTE: It's a near-identical method to _getOverridenMethods for optimisation reasons
536    // we do not want to check for interfaces while creating an interface
537    // and likewise, we do not want to iterate twice through the impl. object's properties to read the interfaces 
538    function _getOverridenMethodsAndImplementedInterfaces(node, config) {
539        var result = [];
540        var overriddenMethodNames = [];
541        var implementedInterfaces = [];
542
543        var interfacesFound = false;
544
545        if (types.isObjectExpression(node)) {
546            var objectProperties = node.properties;
547
548			/*
549				Iterates through all properties of the implementation object, e.g.
550				
551					{
552						method1: function() {
553							
554						},
555						method3: function() {
556							
557						}
558					}
559				
560				will get 'method1' and 'method3'	 
561			*/
562            for (var index in objectProperties) {
563                // if the user has declared interfaces that he is implementing
564                if (!interfacesFound
565                    && objectProperties[index].key.name.toLowerCase() === "interfaces"
566                    && types.isArrayExpression(objectProperties[index].value)) {
567                    interfacesFound = true;
568                    var interfaces = objectProperties[index].value.elements;
569
570                    for (var i in interfaces) {
571                        var interfaceName = _getWholeInterfaceNameFromInterfacesNode(interfaces[i]);
572                        implementedInterfaces.push(interfaceName);
573                    }
574                } else {
575                    overriddenMethodNames.push(objectProperties[index].key.name)
576                }
577            }
578        }
579
580        result.push(overriddenMethodNames);
581        result.push(implementedInterfaces);
582
583        return result;
584    }
585
586    function _getWholeInterfaceNameFromInterfacesNode(node) {
587        var interfaceName = "";
588
589        if (types.isMemberExpression(node)) {
590            interfaceName += _resolveInterfacePath(node.object);
591            interfaceName += node.property.name;
592        }
593
594        return interfaceName;
595    }
596
597    function _resolveInterfacePath(node) {
598        var subNode = "";
599
600        if (types.isMemberExpression(node)) {
601            if (types.isMemberExpression(node.object)) {
602                subNode += _resolveInterfacePath(node.object);
603                subNode += node.property.name + ".";
604            } else {
605                subNode += node.object.name + ".";
606                subNode += node.property.name + ".";
607            }
608        }
609
610        return subNode;
611    }
612
613    function _getWholeName(node) {
614        var arr = [],
615            isAndroidInterface = false;
616
617        while (node !== undefined) {
618            if (!types.isMemberExpression(node)) {
619                if (isAndroidInterface) {
620                    arr.push(node.name)
621                }
622                break;
623            }
624
625            isAndroidInterface = true;
626            arr.push(node.property.name)
627            node = node.object
628        }
629
630        return arr;
631    }
632
633    function _getArgumentFromNodeAsString(path, count, config) {
634
635        var extClassArr = [];
636        var extendedClass = _getParent(path, count, config);
637
638        if (extendedClass) {
639            if (types.isCallExpression(extendedClass.node)) {
640                var o = extendedClass.node.arguments[0];
641            }
642            else {
643                throw {
644                    message: "Node type is not a call expression. File=" + config.filePath + " line=" + path.node.loc.start.line,
645                    errCode: 1
646                }
647            }
648        }
649
650        extClassArr = _getWholeName(o);
651
652        return extClassArr.reverse().join(".");
653    }
654
655    function _getDecoratorArgument(path, config, customDecoratorName) {
656        if (path.parent && types.isCallExpression(path.parent)) {
657
658            if (path.parent.arguments && path.parent.arguments.length > 0) {
659
660                var classNameFromDecorator = path.parent.arguments[0].value
661                var isCorrectExtendClassName = _testJavaProxyName(classNameFromDecorator);
662                if (isCorrectExtendClassName) {
663                    return path.parent.arguments[0].value;
664                }
665                else {
666                    throw {
667                        message: "The first argument '" + classNameFromDecorator + "' of the " + customDecoratorName + " decorator is not following the right pattern which is: '[namespace.]ClassName'. Example: '" + customDecoratorName + "(\"a.b.ClassName\", {overrides...})', file: " + config.filePath,
668                        errCode: 1
669                    }
670                }
671            }
672            else {
673                throw {
674                    message: "No arguments passed to " + customDecoratorName + " decorator. Example: '" + customDecoratorName + "(\"a.b.ClassName\", {overrides...})', file: " + config.filePath,
675                    errCode: 1
676                }
677            }
678        }
679        else {
680            throw {
681                message: "Decorator " + customDecoratorName + " must be called with parameters: Example: '" + customDecoratorName + "(\"a.b.ClassName\", {overrides...})', file: " + config.filePath,
682                errCode: 1
683            }
684        }
685        return undefined;
686    }
687
688    function _getOverriddenMethodsTypescript(path, count) {
689        var overriddenMethods = [];
690
691        var cn = _getParent(path, count)
692
693        // this pattern follows typescript generated syntax
694        for (var item in cn.node.body) {
695            var ci = cn.node.body[item];
696            if (types.isExpressionStatement(ci)) {
697                if (types.isAssignmentExpression(ci.expression)) {
698                    if (ci.expression.left.property) {
699                        overriddenMethods.push(ci.expression.left.property.name)
700                    }
701                }
702            }
703        }
704
705        return overriddenMethods;
706    }
707
708    function _getParent(node, numberOfParents, config) {
709        if (!node) {
710            throw {
711                message: "No parent found for node in file: " + config.filePath,
712                errCode: 1
713            }
714        }
715        if (numberOfParents === 0) {
716            return node;
717        }
718
719        return _getParent(node.parentPath, --numberOfParents)
720    }
721
722    function _testJavaProxyName(name) {
723        if (name) {
724            return /^((\w+\.)+\w+)$/.test(name)
725        }
726        return false;
727    }
728
729    function _testClassName(name) {
730        if (name && name != "") {
731            return /^(\w+)$/.test(name)
732        }
733        return false;
734    }
735
736    function _generateLineToWrite(classNameFromDecorator, extendClass, overriddenMethodNames, extendInfo, filePath, implementedInterfaces = "") {
737        const extendInfoFile = extendInfo.file ? extendInfo.file.replace(/[-\\/\\. ]/g, "_") : "";
738        const extendInfoLine = extendInfo.line ? extendInfo.line : "";
739        const extendInfoColumn = extendInfo.column ? extendInfo.column : "";
740        const extendInfoNewClassName = extendInfo.className ? extendInfo.className : "";
741
742        var lineToWrite = `${extendClass}${ASTERISK_SEPARATOR}`
743            + `${extendInfoFile}${ASTERISK_SEPARATOR}`
744            + `${extendInfoLine}${ASTERISK_SEPARATOR}`
745            + `${extendInfoColumn}${ASTERISK_SEPARATOR}`
746            + `${extendInfoNewClassName}${ASTERISK_SEPARATOR}`
747            + `${overriddenMethodNames}${ASTERISK_SEPARATOR}`
748            + `${classNameFromDecorator}${ASTERISK_SEPARATOR}`
749            + `${filePath}${ASTERISK_SEPARATOR}`
750            + `${implementedInterfaces}`
751
752        return lineToWrite;
753    }
754
755    function addCustomExtend(param, extendPath, lineToWrite) {
756        if (customExtendsArrGlobal.indexOf(param) === -1) {
757            customExtendsArr.push(lineToWrite)
758            customExtendsArrGlobal.push(param)
759        } else {
760            console.log("Warning: there already is an extend called " + param + ".")
761            if (extendPath.indexOf("tns_modules") === -1) {
762                // app folder will take precedence over tns_modules
763                console.log("Warning: The static binding generator will generate extend from:" + extendPath + " implementation")
764                customExtendsArr.push(lineToWrite)
765                customExtendsArrGlobal.push(param)
766            }
767        }
768    }
769
770    return {
771        es5Visitor: es5Visitor
772    }
773})();
774
775module.exports = es5_visitors;
776
Full Screen

proto_test.js

Source: proto_test.js Github

copy
1// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc.  All rights reserved.
3// https://developers.google.com/protocol-buffers/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
8//
9//     * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11//     * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15//     * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31// Test suite is written using Jasmine -- see http://jasmine.github.io/
32
33goog.require('goog.crypt.base64');
34goog.require('goog.testing.asserts');
35goog.require('jspb.Message');
36
37// CommonJS-LoadFromFile: ../testbinary_pb proto.jspb.test
38goog.require('proto.jspb.test.ExtendsWithMessage');
39goog.require('proto.jspb.test.ForeignEnum');
40goog.require('proto.jspb.test.ForeignMessage');
41goog.require('proto.jspb.test.TestAllTypes');
42goog.require('proto.jspb.test.TestExtendable');
43goog.require('proto.jspb.test.extendOptionalBool');
44goog.require('proto.jspb.test.extendOptionalBytes');
45goog.require('proto.jspb.test.extendOptionalDouble');
46goog.require('proto.jspb.test.extendOptionalFixed32');
47goog.require('proto.jspb.test.extendOptionalFixed64');
48goog.require('proto.jspb.test.extendOptionalFloat');
49goog.require('proto.jspb.test.extendOptionalForeignEnum');
50goog.require('proto.jspb.test.extendOptionalInt32');
51goog.require('proto.jspb.test.extendOptionalInt64');
52goog.require('proto.jspb.test.extendOptionalSfixed32');
53goog.require('proto.jspb.test.extendOptionalSfixed64');
54goog.require('proto.jspb.test.extendOptionalSint32');
55goog.require('proto.jspb.test.extendOptionalSint64');
56goog.require('proto.jspb.test.extendOptionalString');
57goog.require('proto.jspb.test.extendOptionalUint32');
58goog.require('proto.jspb.test.extendOptionalUint64');
59goog.require('proto.jspb.test.extendPackedRepeatedBoolList');
60goog.require('proto.jspb.test.extendPackedRepeatedDoubleList');
61goog.require('proto.jspb.test.extendPackedRepeatedFixed32List');
62goog.require('proto.jspb.test.extendPackedRepeatedFixed64List');
63goog.require('proto.jspb.test.extendPackedRepeatedFloatList');
64goog.require('proto.jspb.test.extendPackedRepeatedForeignEnumList');
65goog.require('proto.jspb.test.extendPackedRepeatedInt32List');
66goog.require('proto.jspb.test.extendPackedRepeatedInt64List');
67goog.require('proto.jspb.test.extendPackedRepeatedSfixed32List');
68goog.require('proto.jspb.test.extendPackedRepeatedSfixed64List');
69goog.require('proto.jspb.test.extendPackedRepeatedSint32List');
70goog.require('proto.jspb.test.extendPackedRepeatedSint64List');
71goog.require('proto.jspb.test.extendPackedRepeatedUint32List');
72goog.require('proto.jspb.test.extendPackedRepeatedUint64List');
73goog.require('proto.jspb.test.extendRepeatedBoolList');
74goog.require('proto.jspb.test.extendRepeatedBytesList');
75goog.require('proto.jspb.test.extendRepeatedDoubleList');
76goog.require('proto.jspb.test.extendRepeatedFixed32List');
77goog.require('proto.jspb.test.extendRepeatedFixed64List');
78goog.require('proto.jspb.test.extendRepeatedFloatList');
79goog.require('proto.jspb.test.extendRepeatedForeignEnumList');
80goog.require('proto.jspb.test.extendRepeatedInt32List');
81goog.require('proto.jspb.test.extendRepeatedInt64List');
82goog.require('proto.jspb.test.extendRepeatedSfixed32List');
83goog.require('proto.jspb.test.extendRepeatedSfixed64List');
84goog.require('proto.jspb.test.extendRepeatedSint32List');
85goog.require('proto.jspb.test.extendRepeatedSint64List');
86goog.require('proto.jspb.test.extendRepeatedStringList');
87goog.require('proto.jspb.test.extendRepeatedUint32List');
88goog.require('proto.jspb.test.extendRepeatedUint64List');
89
90
91var suite = {};
92
93var BYTES = new Uint8Array([1, 2, 8, 9]);
94
95var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES);
96
97
98/**
99 * Helper: fill all fields on a TestAllTypes message.
100 * @param {proto.jspb.test.TestAllTypes} msg
101 */
102function fillAllFields(msg) {
103  msg.setOptionalInt32(-42);
104  // can be exactly represented by JS number (64-bit double, i.e., 52-bit
105  // mantissa).
106  msg.setOptionalInt64(-0x7fffffff00000000);
107  msg.setOptionalUint32(0x80000000);
108  msg.setOptionalUint64(0xf000000000000000);
109  msg.setOptionalSint32(-100);
110  msg.setOptionalSint64(-0x8000000000000000);
111  msg.setOptionalFixed32(1234);
112  msg.setOptionalFixed64(0x1234567800000000);
113  msg.setOptionalSfixed32(-1234);
114  msg.setOptionalSfixed64(-0x1234567800000000);
115  msg.setOptionalFloat(1.5);
116  msg.setOptionalDouble(-1.5);
117  msg.setOptionalBool(true);
118  msg.setOptionalString('hello world');
119  msg.setOptionalBytes(BYTES);
120  msg.setOptionalGroup(new proto.jspb.test.TestAllTypes.OptionalGroup());
121  msg.getOptionalGroup().setA(100);
122  var submsg = new proto.jspb.test.ForeignMessage();
123  submsg.setC(16);
124  msg.setOptionalForeignMessage(submsg);
125  msg.setOptionalForeignEnum(proto.jspb.test.ForeignEnum.FOREIGN_FOO);
126  msg.setOneofString('oneof');
127
128
129  msg.setRepeatedInt32List([-42]);
130  msg.setRepeatedInt64List([-0x7fffffff00000000]);
131  msg.setRepeatedUint32List([0x80000000]);
132  msg.setRepeatedUint64List([0xf000000000000000]);
133  msg.setRepeatedSint32List([-100]);
134  msg.setRepeatedSint64List([-0x8000000000000000]);
135  msg.setRepeatedFixed32List([1234]);
136  msg.setRepeatedFixed64List([0x1234567800000000]);
137  msg.setRepeatedSfixed32List([-1234]);
138  msg.setRepeatedSfixed64List([-0x1234567800000000]);
139  msg.setRepeatedFloatList([1.5]);
140  msg.setRepeatedDoubleList([-1.5]);
141  msg.setRepeatedBoolList([true]);
142  msg.setRepeatedStringList(['hello world']);
143  msg.setRepeatedBytesList([BYTES, BYTES]);
144  msg.setRepeatedGroupList([new proto.jspb.test.TestAllTypes.RepeatedGroup()]);
145  msg.getRepeatedGroupList()[0].setA(100);
146  submsg = new proto.jspb.test.ForeignMessage();
147  submsg.setC(1000);
148  msg.setRepeatedForeignMessageList([submsg]);
149  msg.setRepeatedForeignEnumList([proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
150
151  msg.setPackedRepeatedInt32List([-42]);
152  msg.setPackedRepeatedInt64List([-0x7fffffff00000000]);
153  msg.setPackedRepeatedUint32List([0x80000000]);
154  msg.setPackedRepeatedUint64List([0xf000000000000000]);
155  msg.setPackedRepeatedSint32List([-100]);
156  msg.setPackedRepeatedSint64List([-0x8000000000000000]);
157  msg.setPackedRepeatedFixed32List([1234]);
158  msg.setPackedRepeatedFixed64List([0x1234567800000000]);
159  msg.setPackedRepeatedSfixed32List([-1234]);
160  msg.setPackedRepeatedSfixed64List([-0x1234567800000000]);
161  msg.setPackedRepeatedFloatList([1.5]);
162  msg.setPackedRepeatedDoubleList([-1.5]);
163  msg.setPackedRepeatedBoolList([true]);
164
165}
166
167
168/**
169 * Helper: compare a bytes field to an expected value
170 * @param {Uint8Array|string} arr
171 * @param {Uint8Array} expected
172 * @return {boolean}
173 */
174function bytesCompare(arr, expected) {
175  if (goog.isString(arr)) {
176    arr = goog.crypt.base64.decodeStringToUint8Array(arr);
177  }
178  if (arr.length != expected.length) {
179    return false;
180  }
181  for (var i = 0; i < arr.length; i++) {
182    if (arr[i] != expected[i]) {
183      return false;
184    }
185  }
186  return true;
187}
188
189
190/**
191 * Helper: verify contents of given TestAllTypes message as set by
192 * fillAllFields().
193 * @param {proto.jspb.test.TestAllTypes} original
194 * @param {proto.jspb.test.TestAllTypes} copy
195 */
196function checkAllFields(original, copy) {
197  assertTrue(jspb.Message.equals(original, copy));
198
199  assertEquals(copy.getOptionalInt32(), -42);
200  assertEquals(copy.getOptionalInt64(), -0x7fffffff00000000);
201  assertEquals(copy.getOptionalUint32(), 0x80000000);
202  assertEquals(copy.getOptionalUint64(), 0xf000000000000000);
203  assertEquals(copy.getOptionalSint32(), -100);
204  assertEquals(copy.getOptionalSint64(), -0x8000000000000000);
205  assertEquals(copy.getOptionalFixed32(), 1234);
206  assertEquals(copy.getOptionalFixed64(), 0x1234567800000000);
207  assertEquals(copy.getOptionalSfixed32(), -1234);
208  assertEquals(copy.getOptionalSfixed64(), -0x1234567800000000);
209  assertEquals(copy.getOptionalFloat(), 1.5);
210  assertEquals(copy.getOptionalDouble(), -1.5);
211  assertEquals(copy.getOptionalBool(), true);
212  assertEquals(copy.getOptionalString(), 'hello world');
213  assertEquals(true, bytesCompare(copy.getOptionalBytes(), BYTES));
214  assertEquals(true, bytesCompare(copy.getOptionalBytes_asU8(), BYTES));
215  assertEquals(
216      copy.getOptionalBytes_asB64(), goog.crypt.base64.encodeByteArray(BYTES));
217
218  assertEquals(copy.getOptionalGroup().getA(), 100);
219  assertEquals(copy.getOptionalForeignMessage().getC(), 16);
220  assertEquals(copy.getOptionalForeignEnum(),
221      proto.jspb.test.ForeignEnum.FOREIGN_FOO);
222
223
224  assertEquals(copy.getOneofString(), 'oneof');
225  assertEquals(copy.getOneofFieldCase(),
226      proto.jspb.test.TestAllTypes.OneofFieldCase.ONEOF_STRING);
227
228  assertElementsEquals(copy.getRepeatedInt32List(), [-42]);
229  assertElementsEquals(copy.getRepeatedInt64List(), [-0x7fffffff00000000]);
230  assertElementsEquals(copy.getRepeatedUint32List(), [0x80000000]);
231  assertElementsEquals(copy.getRepeatedUint64List(), [0xf000000000000000]);
232  assertElementsEquals(copy.getRepeatedSint32List(), [-100]);
233  assertElementsEquals(copy.getRepeatedSint64List(), [-0x8000000000000000]);
234  assertElementsEquals(copy.getRepeatedFixed32List(), [1234]);
235  assertElementsEquals(copy.getRepeatedFixed64List(), [0x1234567800000000]);
236  assertElementsEquals(copy.getRepeatedSfixed32List(), [-1234]);
237  assertElementsEquals(copy.getRepeatedSfixed64List(), [-0x1234567800000000]);
238  assertElementsEquals(copy.getRepeatedFloatList(), [1.5]);
239  assertElementsEquals(copy.getRepeatedDoubleList(), [-1.5]);
240  assertElementsEquals(copy.getRepeatedBoolList(), [true]);
241  assertElementsEquals(copy.getRepeatedStringList(), ['hello world']);
242  assertEquals(copy.getRepeatedBytesList().length, 2);
243  assertEquals(true, bytesCompare(copy.getRepeatedBytesList_asU8()[0], BYTES));
244  assertEquals(true, bytesCompare(copy.getRepeatedBytesList()[0], BYTES));
245  assertEquals(true, bytesCompare(copy.getRepeatedBytesList_asU8()[1], BYTES));
246  assertEquals(copy.getRepeatedBytesList_asB64()[0], BYTES_B64);
247  assertEquals(copy.getRepeatedBytesList_asB64()[1], BYTES_B64);
248  assertEquals(copy.getRepeatedGroupList().length, 1);
249  assertEquals(copy.getRepeatedGroupList()[0].getA(), 100);
250  assertEquals(copy.getRepeatedForeignMessageList().length, 1);
251  assertEquals(copy.getRepeatedForeignMessageList()[0].getC(), 1000);
252  assertElementsEquals(copy.getRepeatedForeignEnumList(),
253      [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
254
255  assertElementsEquals(copy.getPackedRepeatedInt32List(), [-42]);
256  assertElementsEquals(copy.getPackedRepeatedInt64List(),
257      [-0x7fffffff00000000]);
258  assertElementsEquals(copy.getPackedRepeatedUint32List(), [0x80000000]);
259  assertElementsEquals(copy.getPackedRepeatedUint64List(),
260      [0xf000000000000000]);
261  assertElementsEquals(copy.getPackedRepeatedSint32List(), [-100]);
262  assertElementsEquals(copy.getPackedRepeatedSint64List(),
263      [-0x8000000000000000]);
264  assertElementsEquals(copy.getPackedRepeatedFixed32List(), [1234]);
265  assertElementsEquals(copy.getPackedRepeatedFixed64List(),
266      [0x1234567800000000]);
267  assertElementsEquals(copy.getPackedRepeatedSfixed32List(), [-1234]);
268  assertElementsEquals(copy.getPackedRepeatedSfixed64List(),
269      [-0x1234567800000000]);
270  assertElementsEquals(copy.getPackedRepeatedFloatList(), [1.5]);
271  assertElementsEquals(copy.getPackedRepeatedDoubleList(), [-1.5]);
272
273}
274
275
276/**
277 * Helper: verify that all expected extensions are present.
278 * @param {!proto.jspb.test.TestExtendable} msg
279 */
280function checkExtensions(msg) {
281  assertEquals(-42,
282      msg.getExtension(proto.jspb.test.extendOptionalInt32));
283  assertEquals(-0x7fffffff00000000,
284      msg.getExtension(proto.jspb.test.extendOptionalInt64));
285  assertEquals(0x80000000,
286      msg.getExtension(proto.jspb.test.extendOptionalUint32));
287  assertEquals(0xf000000000000000,
288      msg.getExtension(proto.jspb.test.extendOptionalUint64));
289  assertEquals(-100,
290      msg.getExtension(proto.jspb.test.extendOptionalSint32));
291  assertEquals(-0x8000000000000000,
292      msg.getExtension(proto.jspb.test.extendOptionalSint64));
293  assertEquals(1234,
294      msg.getExtension(proto.jspb.test.extendOptionalFixed32));
295  assertEquals(0x1234567800000000,
296      msg.getExtension(proto.jspb.test.extendOptionalFixed64));
297  assertEquals(-1234,
298      msg.getExtension(proto.jspb.test.extendOptionalSfixed32));
299  assertEquals(-0x1234567800000000,
300      msg.getExtension(proto.jspb.test.extendOptionalSfixed64));
301  assertEquals(1.5,
302      msg.getExtension(proto.jspb.test.extendOptionalFloat));
303  assertEquals(-1.5,
304      msg.getExtension(proto.jspb.test.extendOptionalDouble));
305  assertEquals(true,
306      msg.getExtension(proto.jspb.test.extendOptionalBool));
307  assertEquals('hello world',
308      msg.getExtension(proto.jspb.test.extendOptionalString));
309  assertEquals(
310      true, bytesCompare(
311                msg.getExtension(proto.jspb.test.extendOptionalBytes), BYTES));
312  assertEquals(16,
313      msg.getExtension(
314          proto.jspb.test.ExtendsWithMessage.optionalExtension).getFoo());
315
316
317  assertElementsEquals(
318      msg.getExtension(proto.jspb.test.extendRepeatedInt32List),
319      [-42]);
320  assertElementsEquals(
321      msg.getExtension(proto.jspb.test.extendRepeatedInt64List),
322      [-0x7fffffff00000000]);
323  assertElementsEquals(
324      msg.getExtension(proto.jspb.test.extendRepeatedUint32List),
325      [0x80000000]);
326  assertElementsEquals(
327      msg.getExtension(proto.jspb.test.extendRepeatedUint64List),
328      [0xf000000000000000]);
329  assertElementsEquals(
330      msg.getExtension(proto.jspb.test.extendRepeatedSint32List),
331      [-100]);
332  assertElementsEquals(
333      msg.getExtension(proto.jspb.test.extendRepeatedSint64List),
334      [-0x8000000000000000]);
335  assertElementsEquals(
336      msg.getExtension(proto.jspb.test.extendRepeatedFixed32List),
337      [1234]);
338  assertElementsEquals(
339      msg.getExtension(proto.jspb.test.extendRepeatedFixed64List),
340      [0x1234567800000000]);
341  assertElementsEquals(
342      msg.getExtension(proto.jspb.test.extendRepeatedSfixed32List),
343      [-1234]);
344  assertElementsEquals(
345      msg.getExtension(proto.jspb.test.extendRepeatedSfixed64List),
346      [-0x1234567800000000]);
347  assertElementsEquals(
348      msg.getExtension(proto.jspb.test.extendRepeatedFloatList),
349      [1.5]);
350  assertElementsEquals(
351      msg.getExtension(proto.jspb.test.extendRepeatedDoubleList),
352      [-1.5]);
353  assertElementsEquals(
354      msg.getExtension(proto.jspb.test.extendRepeatedBoolList),
355      [true]);
356  assertElementsEquals(
357      msg.getExtension(proto.jspb.test.extendRepeatedStringList),
358      ['hello world']);
359  assertEquals(
360      true,
361      bytesCompare(
362          msg.getExtension(proto.jspb.test.extendRepeatedBytesList)[0], BYTES));
363  assertEquals(1000,
364      msg.getExtension(
365          proto.jspb.test.ExtendsWithMessage.repeatedExtensionList)[0]
366      .getFoo());
367  assertElementsEquals(
368      msg.getExtension(proto.jspb.test.extendRepeatedForeignEnumList),
369      [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
370
371
372  assertElementsEquals(
373      msg.getExtension(proto.jspb.test.extendPackedRepeatedInt32List),
374      [-42]);
375  assertElementsEquals(
376      msg.getExtension(proto.jspb.test.extendPackedRepeatedInt64List),
377      [-0x7fffffff00000000]);
378  assertElementsEquals(
379      msg.getExtension(proto.jspb.test.extendPackedRepeatedUint32List),
380      [0x80000000]);
381  assertElementsEquals(
382      msg.getExtension(proto.jspb.test.extendPackedRepeatedUint64List),
383      [0xf000000000000000]);
384  assertElementsEquals(
385      msg.getExtension(proto.jspb.test.extendPackedRepeatedSint32List),
386      [-100]);
387  assertElementsEquals(
388      msg.getExtension(proto.jspb.test.extendPackedRepeatedSint64List),
389      [-0x8000000000000000]);
390  assertElementsEquals(
391      msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed32List),
392      [1234]);
393  assertElementsEquals(
394      msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed64List),
395      [0x1234567800000000]);
396  assertElementsEquals(
397      msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed32List),
398      [-1234]);
399  assertElementsEquals(
400      msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed64List),
401      [-0x1234567800000000]);
402  assertElementsEquals(
403      msg.getExtension(proto.jspb.test.extendPackedRepeatedFloatList),
404      [1.5]);
405  assertElementsEquals(
406      msg.getExtension(proto.jspb.test.extendPackedRepeatedDoubleList),
407      [-1.5]);
408  assertElementsEquals(
409      msg.getExtension(proto.jspb.test.extendPackedRepeatedBoolList),
410      [true]);
411  assertElementsEquals(
412      msg.getExtension(proto.jspb.test.extendPackedRepeatedForeignEnumList),
413      [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
414
415}
416
417
418describe('protoBinaryTest', function() {
419  /**
420   * Tests a basic serialization-deserializaton round-trip with all supported
421   * field types (on the TestAllTypes message type).
422   */
423  it('testRoundTrip', function() {
424    var msg = new proto.jspb.test.TestAllTypes();
425    fillAllFields(msg);
426    var encoded = msg.serializeBinary();
427    var decoded = proto.jspb.test.TestAllTypes.deserializeBinary(encoded);
428    checkAllFields(msg, decoded);
429  });
430
431  /**
432   * Test that base64 string and Uint8Array are interchangeable in bytes fields.
433   */
434  it('testBytesFieldsGettersInterop', function() {
435    var msg = new proto.jspb.test.TestAllTypes();
436    // Set from a base64 string and check all the getters work.
437    msg.setOptionalBytes(BYTES_B64);
438    assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
439    assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
440    assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
441
442    // Test binary serialize round trip doesn't break it.
443    msg = proto.jspb.test.TestAllTypes.deserializeBinary(msg.serializeBinary());
444    assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
445    assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
446    assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
447
448    msg = new proto.jspb.test.TestAllTypes();
449    // Set from a Uint8Array and check all the getters work.
450    msg.setOptionalBytes(BYTES);
451    assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
452    assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
453    assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
454
455  });
456
457  /**
458   * Test that bytes setters will receive result of any of the getters.
459   */
460  it('testBytesFieldsSettersInterop', function() {
461    var msg = new proto.jspb.test.TestAllTypes();
462    msg.setOptionalBytes(BYTES);
463    assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
464
465    msg.setOptionalBytes(msg.getOptionalBytes());
466    assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
467    msg.setOptionalBytes(msg.getOptionalBytes_asB64());
468    assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
469    msg.setOptionalBytes(msg.getOptionalBytes_asU8());
470    assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
471  });
472
473  /**
474   * Test that bytes setters will receive result of any of the getters.
475   */
476  it('testRepeatedBytesGetters', function() {
477    var msg = new proto.jspb.test.TestAllTypes();
478
479    function assertGetters() {
480      assertTrue(goog.isString(msg.getRepeatedBytesList_asB64()[0]));
481      assertTrue(goog.isString(msg.getRepeatedBytesList_asB64()[1]));
482      assertTrue(msg.getRepeatedBytesList_asU8()[0] instanceof Uint8Array);
483      assertTrue(msg.getRepeatedBytesList_asU8()[1] instanceof Uint8Array);
484
485      assertTrue(bytesCompare(msg.getRepeatedBytesList()[0], BYTES));
486      assertTrue(bytesCompare(msg.getRepeatedBytesList()[1], BYTES));
487      assertTrue(bytesCompare(msg.getRepeatedBytesList_asB64()[0], BYTES));
488      assertTrue(bytesCompare(msg.getRepeatedBytesList_asB64()[1], BYTES));
489      assertTrue(bytesCompare(msg.getRepeatedBytesList_asU8()[0], BYTES));
490      assertTrue(bytesCompare(msg.getRepeatedBytesList_asU8()[1], BYTES));
491    }
492
493    msg.setRepeatedBytesList([BYTES, BYTES]);
494    assertGetters();
495
496    msg.setRepeatedBytesList([BYTES_B64, BYTES_B64]);
497    assertGetters();
498
499    msg.setRepeatedBytesList([]);
500    assertEquals(0, msg.getRepeatedBytesList().length);
501    assertEquals(0, msg.getRepeatedBytesList_asB64().length);
502    assertEquals(0, msg.getRepeatedBytesList_asU8().length);
503  });
504
505  /**
506   * Helper: fill all extension values.
507   * @param {proto.jspb.test.TestExtendable} msg
508   */
509  function fillExtensions(msg) {
510    msg.setExtension(
511        proto.jspb.test.extendOptionalInt32, -42);
512    msg.setExtension(
513        proto.jspb.test.extendOptionalInt64, -0x7fffffff00000000);
514    msg.setExtension(
515        proto.jspb.test.extendOptionalUint32, 0x80000000);
516    msg.setExtension(
517        proto.jspb.test.extendOptionalUint64, 0xf000000000000000);
518    msg.setExtension(
519        proto.jspb.test.extendOptionalSint32, -100);
520    msg.setExtension(
521        proto.jspb.test.extendOptionalSint64, -0x8000000000000000);
522    msg.setExtension(
523        proto.jspb.test.extendOptionalFixed32, 1234);
524    msg.setExtension(
525        proto.jspb.test.extendOptionalFixed64, 0x1234567800000000);
526    msg.setExtension(
527        proto.jspb.test.extendOptionalSfixed32, -1234);
528    msg.setExtension(
529        proto.jspb.test.extendOptionalSfixed64, -0x1234567800000000);
530    msg.setExtension(
531        proto.jspb.test.extendOptionalFloat, 1.5);
532    msg.setExtension(
533        proto.jspb.test.extendOptionalDouble, -1.5);
534    msg.setExtension(
535        proto.jspb.test.extendOptionalBool, true);
536    msg.setExtension(
537        proto.jspb.test.extendOptionalString, 'hello world');
538    msg.setExtension(proto.jspb.test.extendOptionalBytes, BYTES);
539    var submsg = new proto.jspb.test.ExtendsWithMessage();
540    submsg.setFoo(16);
541    msg.setExtension(
542        proto.jspb.test.ExtendsWithMessage.optionalExtension, submsg);
543    msg.setExtension(
544        proto.jspb.test.extendOptionalForeignEnum,
545        proto.jspb.test.ForeignEnum.FOREIGN_FOO);
546
547
548    msg.setExtension(
549        proto.jspb.test.extendRepeatedInt32List, [-42]);
550    msg.setExtension(
551        proto.jspb.test.extendRepeatedInt64List, [-0x7fffffff00000000]);
552    msg.setExtension(
553        proto.jspb.test.extendRepeatedUint32List, [0x80000000]);
554    msg.setExtension(
555        proto.jspb.test.extendRepeatedUint64List, [0xf000000000000000]);
556    msg.setExtension(
557        proto.jspb.test.extendRepeatedSint32List, [-100]);
558    msg.setExtension(
559        proto.jspb.test.extendRepeatedSint64List, [-0x8000000000000000]);
560    msg.setExtension(
561        proto.jspb.test.extendRepeatedFixed32List, [1234]);
562    msg.setExtension(
563        proto.jspb.test.extendRepeatedFixed64List, [0x1234567800000000]);
564    msg.setExtension(
565        proto.jspb.test.extendRepeatedSfixed32List, [-1234]);
566    msg.setExtension(
567        proto.jspb.test.extendRepeatedSfixed64List, [-0x1234567800000000]);
568    msg.setExtension(
569        proto.jspb.test.extendRepeatedFloatList, [1.5]);
570    msg.setExtension(
571        proto.jspb.test.extendRepeatedDoubleList, [-1.5]);
572    msg.setExtension(
573        proto.jspb.test.extendRepeatedBoolList, [true]);
574    msg.setExtension(
575        proto.jspb.test.extendRepeatedStringList, ['hello world']);
576    msg.setExtension(proto.jspb.test.extendRepeatedBytesList, [BYTES]);
577    submsg = new proto.jspb.test.ExtendsWithMessage();
578    submsg.setFoo(1000);
579    msg.setExtension(
580        proto.jspb.test.ExtendsWithMessage.repeatedExtensionList, [submsg]);
581    msg.setExtension(proto.jspb.test.extendRepeatedForeignEnumList,
582        [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
583
584
585    msg.setExtension(
586        proto.jspb.test.extendPackedRepeatedInt32List, [-42]);
587    msg.setExtension(
588        proto.jspb.test.extendPackedRepeatedInt64List, [-0x7fffffff00000000]);
589    msg.setExtension(
590        proto.jspb.test.extendPackedRepeatedUint32List, [0x80000000]);
591    msg.setExtension(
592        proto.jspb.test.extendPackedRepeatedUint64List, [0xf000000000000000]);
593    msg.setExtension(
594        proto.jspb.test.extendPackedRepeatedSint32List, [-100]);
595    msg.setExtension(
596        proto.jspb.test.extendPackedRepeatedSint64List, [-0x8000000000000000]);
597    msg.setExtension(
598        proto.jspb.test.extendPackedRepeatedFixed32List, [1234]);
599    msg.setExtension(
600        proto.jspb.test.extendPackedRepeatedFixed64List, [0x1234567800000000]);
601    msg.setExtension(
602        proto.jspb.test.extendPackedRepeatedSfixed32List, [-1234]);
603    msg.setExtension(
604        proto.jspb.test.extendPackedRepeatedSfixed64List,
605        [-0x1234567800000000]);
606    msg.setExtension(
607        proto.jspb.test.extendPackedRepeatedFloatList, [1.5]);
608    msg.setExtension(
609        proto.jspb.test.extendPackedRepeatedDoubleList, [-1.5]);
610    msg.setExtension(
611        proto.jspb.test.extendPackedRepeatedBoolList, [true]);
612    msg.setExtension(proto.jspb.test.extendPackedRepeatedForeignEnumList,
613        [proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
614
615  }
616
617
618  /**
619   * Tests extension serialization and deserialization.
620   */
621  it('testExtensions', function() {
622    var msg = new proto.jspb.test.TestExtendable();
623    fillExtensions(msg);
624    var encoded = msg.serializeBinary();
625    var decoded = proto.jspb.test.TestExtendable.deserializeBinary(encoded);
626    checkExtensions(decoded);
627  });
628});
629
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)