Best Python code snippet using avocado_python
gendoc.es
Source:gendoc.es
...56 throw usage()57 }58 return files59 }60 function emit(...args) {61 out.write(args.toString() + "\n")62 }63 function emitHeader() {64 if (bare) {65 return66 }67 emit('<!DOCTYPE html>')68 emit('<html lang="en">')69 emit('<head>')70 emit('<meta charset="utf-8"/>')71 emit('<title>' + title + ' Documentation</title>')72 emit('<link href="api.css" rel="stylesheet" type="text/css" />')73 emit('</head>\n<body>\n')74 emit(' <div class="contents">')75 }76 function emitFooter() {77 if (bare) {78 return79 }80 emit('<div class="footnote">Generated on ' + new Date + '<br/>')81 emit(' Copyright © <a href="http://embedthis.com">Embedthis Software</a> ' + 82 new Date().year + '.')83 emit('</div></div></body></html>')84 }85 /*86 Emit top level navigation87 */88 function emitNavigation() {89 if (bare) {90 return91 }92 emit('<div>')93 result = []94 for each (kind in ["Extensions", "Typedefs", "Functions", "Defines"]) {95 result.append('<a href="#' + kind + '">' + kind + '</a>')96 }97 emit(result.join(" | "))98 emit('</div>')99 }100 /*101 Parse all symbol references and build an index of symbols102 */103 function parseReferences(xml: XML) {104 for each (def in xml) {105 if (def.@kind == "group" || def.@kind == "struct") {106 symbols[def.compoundname] = def.@id107 for each (sect in def.detaileddescription.para.simplesect) {108 if (sect.@kind != "see") {109 continue110 }111 seeAlso[def.compoundname] = sect.para112 }113 }114 }115 var sections: XML = xml.compounddef.sectiondef116 for each (section in sections) {117 var members: XML = section.memberdef118 for each (m in members) {119 if (m.name != "" && m.@id != "") {120 symbols[m.name] = m.@id121 }122 }123 }124 }125 /*126 Emit a reference127 */128 function ref(name: String): String {129 /* Split the core type name off from "*" suffixes */130 parts = name.split(" ")131 typeSpec = parts.slice(0, 1)132 rest = parts.slice(1)133 sym = typeSpec.toString().trim("*")134 let value = symbols[sym]135 if (value) {136 let result137 if (value.toString().contains("#")) {138 result = '<a href="' + symbols[sym] + '" class="ref">' + typeSpec + '</a>'139 } else {140 result = '<a href="#' + symbols[sym] + '" class="ref">' + typeSpec + '</a>'141 }142 if (rest && rest != "") {143 result += " " + rest144 }145 return result146 }147 if (!reserved[sym]) {148 App.log.error("Cannot find link symbol \"" + sym + "\"")149 }150 return name151 }152 function strip(str: String): String {153 if (str == "") {154 return str155 }156 str = str.replace(/<para>|<emphasis>|<title>|<type>|<\/para>|<\/emphasis>|<\/title>|<\/type>/g, "")157 str = str.replace(/<ref refid="[^>]*>/g, '')158 str = str.replace(/<\/ref>/g, '')159 str = str.replace(/ kindref="[^"]*"/g, '')160 str = str.replace(/itemizedlist>/g, '')161 str = str.replace(/listitem>/g, '')162 str = str.replace(/<linebreak\/>/g, '')163 str = str.replace(/bold>/g, '')164 str = str.trim().trim(".").trim().trim(".")165 return str166 }167 /*168 Remove or map XML elements into HTML169 */170 function clean(str: String): String {171 if (str == "") {172 return str173 }174 str = str.replace(/<para>|<emphasis>|<title>|<type>|<\/para>|<\/emphasis>|<\/title>|<\/type>/g, "")175 str = str.replace(/<ref refid="([^"]*#[^"]*)"/g, '<a class="ref" AAA href="$1"')176 str = str.replace(/<ref refid="/g, '<a class="ref" href="#')177 str = str.replace(/<\/ref>/g, '</a>')178 str = str.replace(/ kindref="[^"]*"/g, "")179 str = str.replace(/itemizedlist>/g, 'ul>')180 str = str.replace(/listitem>/g, 'li>')181 str = str.replace(/<linebreak\/>/g, "<br/>")182 str = str.replace(/bold>/g, "b>")183 str = str.replace(/preformatted>/g, "pre>")184 str = str.replace(/<row>/g, "<tr>")185 str = str.replace(/<entry thead="no">/g, "<td>")186 str = str.replace(/<table rows=[^>]*>/g, "<table class='info'>")187 str = str.replace(/<\/entry>/g, "</td>")188 str = str.trim().trim(".").trim().trim(".")189 str = str.replace(/--/g, "—")190 return str191 }192 /*193 Clean the string of XML elements and append a "."194 */195 function cleanDot(str: String): String {196 s = clean(str)197 if (s == "") {198 return s199 }200 if (!s.endsWith(">")) {201 s = s + "."202 }203 return s204 }205 /*206 Intelligently transform a @return directive207 */208 function cleanReturns(str: String): String {209 str = cleanDot(str)210 str = str.replace(/^Return[s]* the/, "The")211 return str212 }213 /*214 Emit a file level overview215 */216 function emitOverview(xml: XML) {217 emit("<h1>" + title + "</h1>")218 for each (def in xml) {219 if (def.@kind != "file") {220 continue221 }222 name = def.compoundname223 if (!all && def.briefdescription == '' && def.detaileddescription == '') {224 return225 }226 emit('<a name="' + name + '"></a>')227 if (def.briefdescription != "") {228 emit('<p>' + cleanDot(def.briefdescription.para) + '</p>')229 }230 if (def.detaileddescription != "") {231 for each (node in def.detaileddescription.*) {232 str = node.toString()233 str = str.replace(/para>/g, "p>")234 str = str.replace(/title>/g, "h1>")235 str = str.replace(/<linebreak\/>/g, "<br/>")236 str = str.replace(/<sect[^>]*>|<\/sect[0-9]>/g, "")237 str = str.replace(/<simplesect[^>]*>|<\/simplesect>/g, "")238 emit(str)239 }240 }241 }242 }243 /*244 Emit an index of all services245 */246 function emitServiceIndex(def: XML) {247 if (all || def.briefdescription != "" || def.detaileddescription != '') {248 emit('<tr class="apiDef">')249 emit('<td class="apiName"><a href="#' + def.@id + '" class="nameRef">' + def.compoundname + '</a></td>')250 emit('<td class="apiBrief">' + cleanDot(def.briefdescription.para) + '</td></tr>')251 }252 symbols[def.compoundname] = def.@id253 }254 /*255 Generate an index of all functions256 */257 function genFunctionIndex(def: XML, section: XML, index: Object) {258 var members: XML = section.memberdef259 for each (m in members) {260 if (m.@kind == 'function') {261 if (!all && m.briefdescription == '' && m.detaileddescription == '') {262 continue263 }264 if (def.@kind == "file" && m.@id.toString().startsWith("group__")) {265 continue266 }267 let definition = m.definition.toString().split(" ")268 typedef = definition.slice(0, -1).join(" ")269 name = definition.slice(-1)270 let str = '<tr class="apiDef"><td class="apiType">' + ref(typedef) + '</td><td>'271 str += '<a href="#' + m.@id + '" class="nameRef">' + name + '</a>'272 args = m.argsstring.toString().trim('(').split(",")273 if (args.length > 0) {274 result = []275 for (i in args) {276 arg = args[i].trim()277 result.append(ref(arg))278 }279 str += "(" + result.join(", ")280 }281 str += '</td></tr>'282 if (m.briefdescription != "") {283 str += '<tr class="apiBrief"><td> </td><td>' + cleanDot(m.briefdescription.para) + '</td></tr>'284 }285 index[name] = str286 }287 }288 }289 /*290 Emit an index of all #define directives291 */292 function emitDefineIndex(section: XML) {293 var members: XML = section.memberdef294 for each (m in members) {295 if (m.@kind == 'define') {296 if (!all && m.briefdescription == '' && m.detaileddescription == '') {297 continue298 }299 symbols[m.name] = m.@id300 emit('<tr class="apiDef">')301 emit('<td>#define</td><td><a href="#' + m.@id + '" class="nameRef">' + m.name + '</a>' + 302 ' ' + m.initializer + '</td>')303 emit('</tr>')304 if (m.briefdescription != "") {305 emit('<tr class="apiBrief"><td> </td><td>' + 306 cleanDot(m.briefdescription.para) + '</td></tr>')307 }308 }309 }310 }311 /*312 Emit an index of struct based typedefs313 */314 function emitTypeIndex(def: XML, index: Object) {315 var str316 if (all || def.briefdescription != "" || def.detaileddescription != '') {317 name = def.compoundname318 symbols[name] = def.@id319 str = '<tr class="apiDef">'320 str += '<td class="apiName">'321 str += '<a href="#' + symbols[name] + '" class="nameRef">' + name + '</a></td>'322 str += '<td class="apiBrief">' + cleanDot(def.briefdescription.para) + '</td></tr>'323 index[name] = str324 }325 }326 /*327 Emit an index of all simple (non-struct) typedefs328 */329 function emitStructTypeIndex(section: XML, index: Object) {330 var members: XML = section.memberdef331 var str332 for each (m in members) {333 if (m.@kind == 'typedef') {334 if (!all && m.briefdescription == '' && m.detaileddescription == '') {335 continue336 }337 symbols[m.name] = m.@id338 def = m.definition.toString()339 if (def.contains("(")) {340 /* Parse "typedef void(* MprLogHandler)(cchar *file, ... cchar *msg) */341 name = def.toString().replace(/typedef[^\(]*\([^\w]*([\w]+).*/, "$1")342 } else {343 def = def.toString().split(" ")344 typedef = def.slice(0, -1).join(" ")345 name = def.slice(-1)346 }347 str = '<tr class="apiDef">'348 str += '<td class="apiName">'349 str += '<a href="#' + m.@id + '" class="nameRef">' + name + '</a></td>'350 if (m.briefdescription != "") {351 str += '<td class="apiBrief">' + cleanDot(m.briefdescription.para) + '</td></tr>'352 }353 index[name] = str354 }355 }356 }357 /*358 Get master group references for a given group name359 */360 function getGroupReferences(group: String): Array {361 references = []362 items = seeAlso[group]363 if (items != undefined) {364 for each (see in items.ref.*) {365 references.append(see)366 }367 }368 return references369 }370 /*371 Emit a See Also section. Handle groups/struct @references372 */373 function emitSeeAlso(name: String, node: XML) {374 if (node.para.toString().startsWith('@-')) {375 let name = node.para.toString().slice(2).trim()376 references = getGroupReferences(name)377 } else {378 references = []379 for each (see in node.para.ref.*) {380 references.append(see)381 }382 }383 emitSeeAlsoReferences(name, references)384 }385 function emitSeeAlsoReferences(name: String, references: Array) {386 emit(' <dl><dt>See Also:</dt><dd>')387 references.sort()388 trimmed = []389 for each (see in references) {390 if (see == name) {391 continue392 }393 trimmed.append(ref(see))394 }395 emit(' ' + trimmed.join(", ") + '</dd></dl>')396 }397 function emitSimpleSect(name: String, node: XML) {398 if (node.@kind == "see") {399 emitSeeAlso(name, node)400 } else if (node.@kind == "return") {401 emit(' <dl><dt>Returns:</dt><dd>' + cleanReturns(node.para).toPascal() + '</dd></dl>')402 } else if (node.@kind == "remark") {403 emit(' <dl><dt>Remarks:</dt><dd>' + cleanDot(node.para).toPascal() + '</dd></dl>')404 } else {405 emit(' <dl><dt>' + clean(node.title) + '</dt><dd>' + cleanDot(node.para).toPascal() + '</dd></dl>')406 }407 }408 /*409 Emit function args410 */411 function emitArgs(args: XML) {412 result = []413 for each (p in args.param) {414 if (p.type == "...") {415 result.append("...")416 } else {417 s = ref(strip(p.type)) + " " + p.declname418 s = s.replace(/ ([\*]*) /, " $1")419 result.append(s)420 }421 }422 emit("(" + result.join(", ") + ")")423 }424 /*425 Used for function and simple typedef details426 */427 function emitDetail(def: XML, section: XML) {428 var members: XML = section.memberdef429 if (section.@kind == "func") {430 kind = "function"431 } else if (section.@kind == "typedef") {432 kind = "typedef"433 }434 for each (m in members) {435 if (m.@kind == kind) {436 if (!all && m.briefdescription == '' && m.detaileddescription == '') {437 continue438 }439 if (def.@kind == "file" && m.@id.toString().startsWith("group__")) {440 continue441 }442 emit('<a name="' + m.@id + '"></a>')443 emit('<div class="api">')444 emit(' <div class="prototype">')445 if (kind == "function") {446 emit(' ' + ref(strip(m.type)))447 str = m.definition.toString().split(" ").slice(1).join(" ")448 emit(' ' + clean(str))449 emitArgs(m)450 } else if (kind == "typedef") {451 emit(' ' + cleanDot(m.definition))452 }453 emit(' </div>')454 emit(' <div class="apiDetail">')455 if (m.briefdescription != "") {456 emit('<p>' + cleanDot(m.briefdescription.para) + '</p>')457 }458 seen = false459 for each (n in m.detaileddescription.para.*) {460 if (n.name() == "simplesect") {461 if (n.@kind == "see") {462 seen = true463 }464 emitSimpleSect(m.name, n)465 } else if (n.name() == "parameterlist") {466 /*467 Parameters468 */469 emit(' <dl><dt>Parameters:</dt><dd>')470 emit(' <table class="parameters" title="Parameters">')471 for each (p in n.parameteritem) {472 emit(' <tr><td class="param">' + p.parameternamelist.parametername + '</td><td>' + 473 cleanDot(p.parameterdescription.para) + '</td>')474 }475 emit(' </table></dd></dl>')476 } else {477 emit(clean(n))478 }479 }480 if (!seen && def.@kind == "group") {481 references = getGroupReferences(def.compoundname)482 emitSeeAlsoReferences(m.name, references)483 }484 emit(' </div>')485 emit('</div>')486 }487 }488 }489 function emitFields(name: String, def: XML) {490 let doneHeader = false491 for each (m in def.sectiondef.memberdef) {492 if (!doneHeader) {493 emit(' <dl><dt>Fields:</dt><dd>')494 emit(' <table class="parameters" title="Parameters">')495 doneHeader = true496 }497 if (m.@kind == "variable") {498 field = m.definition.toString().replace(/.*::/, "")499 if (m.briefdescription != "" || m.detaileddescription != "") {500 emit(' <tr><td class="param">' + clean(m.type) + '</td><td><td>' + field + '</td><td>')501 if (m.briefdescription != "") {502 s = cleanDot(m.briefdescription.para)503 if (m.detaileddescription != "") {504 s += " "505 }506 emit(s)507 }508 if (m.detaileddescription != "") {509 s = cleanDot(m.detaileddescription.para)510 emit(s)511 }512 emit('</td>')513 }514 }515 }516 if (doneHeader) {517 emit(' </table></dd></dl>')518 }519 }520 function emitStructDetail(def: XML, fields: XML?) {521 let name = def.compoundname522 if (!all && def.briefdescription == '' && def.detaileddescription == '') {523 return524 }525 emit('<a name="' + symbols[name] + '"></a>')526 emit('<div class="api">')527 emit(' <div class="prototype">' + clean(name) + '</div>')528 emit(' <div class="apiDetail">')529 if (def.briefdescription != "") {530 emit('<p>' + cleanDot(def.briefdescription.para) + '</p>')531 }532 let doneFields = false533 if (def.detaileddescription != "") {534 for each (n in def.detaileddescription.para.*) {535 if (n.name() == "simplesect") {536 emitSimpleSect(name, n)537 if (!doneFields && fields == null) {538 emitFields(name, def)539 doneFields = true540 }541 }542 }543 }544 if (fields) {545 emitFields(name, fields)546 } else if (!doneFields) {547 emitFields(name, def)548 }549 emit(' </div>')550 emit('</div>')551 }552 function emitIndicies(xml: XML) {553 var sections: XML554 /*555 Emit the group indicies556 */557 emit('<a name="Extensions"></a><h1>Extensions</h1>')558 emit(' <table class="apiIndex" title="Extensions">')559 for each (def in xml) {560 if (def.@kind == "group") {561 emitServiceIndex(def)562 }563 }564 emit('</table>')565 /*566 Emit the navigation indicies567 */568 emit('<a name="Functions"></a><h1>Functions</h1>')569 emit(' <table class="apiIndex" title="Functions">')570 let functionIndex = {}571 for each (def in xml) {572 sections = def.sectiondef573 for each (section in sections) {574 if (section.@kind == "func") {575 genFunctionIndex(def, section, functionIndex)576 }577 }578 }579 Object.sortProperties(functionIndex)580 for each (i in functionIndex) {581 emit(i)582 }583 emit('</table>')584 emit('<a name="Typedefs"></a><h1>Typedefs</h1>')585 emit('<table class="apiIndex" title="typedefs">')586 let typeIndex = {}587 for each (def in xml) {588 if (def.@kind == "struct") {589 emitTypeIndex(def, typeIndex)590 } else {591 sections = def.sectiondef592 for each (section in sections) {593 if (section.@kind == "typedef") {594 emitStructTypeIndex(section, typeIndex)595 }596 }597 }598 }599 Object.sortProperties(typeIndex)600 for each (i in typeIndex) {601 emit(i)602 }603 emit('</table>')604 emit('<a name="Defines"></a><h1>Defines</h1>')605 emit('<table class="apiIndex" title="Defines">')606 for each (def in xml) {607 sections = def.sectiondef608 for each (section in sections) {609 if (section.@kind == "define") {610 emitDefineIndex(section)611 }612 }613 }614 emit(" </table>")615 }616 function emitDetails(xml: XML) {617 /*618 Emit groups619 */620 for each (def in xml) {621 if (def.@kind != "group") {622 continue623 }624 emit('<h1>' + def.compoundname + '</h1>')625 let foundStruct = false626 for each (d in xml) {627 if (d.@kind == "struct" && d.compoundname.toString() == def.compoundname.toString()) {628 foundStruct = true629 emitStructDetail(def, d)630 }631 }632 if (!foundStruct) {633 for each (d in xml) {634 if (d.compoundname.toString() == def.compoundname.toString()) {635 emitStructDetail(def, d)636 }637 }638 }639 let sections: XML = def.sectiondef640 for each (section in sections) {641 if (section.@kind == "func") {642 emitDetail(def, section)643 }644 }645 }646 /*647 Emit functions648 */649 emit('<h2>Functions</h2>')650 for each (def in xml) {651 if (def.@kind == "group") {652 continue653 }654 let sections: XML = def.sectiondef655 for each (section in sections) {656 if (section.@kind == "func") {657 emitDetail(def, section)658 }659 }660 }661 emit('<h2>Typedefs</h2>')662 for each (def in xml) {663 if (def.@kind == "struct") {664 emitStructDetail(def, null)665 } else {666 let sections: XML = def.sectiondef667 for each (section in sections) {668 if (section.@kind == "typedef") {669 emitDetail(def, section)670 }671 }672 }673 }674 }675 function parse(xml: XML) {...
ObjectModelSpec.js
Source:ObjectModelSpec.js
...38 children: []39 });40 });41 it('should add spec and create describe blocks on SpecBegin event', function() {42 runner.emit('SpecBegin', buildSpec(1, 'test spec', ['describe 2', 'describe 1']));43 expect(model.value.children['describe 1']).toBeDefined();44 expect(model.value.children['describe 1'].children['describe 2']).toBeDefined();45 expect(model.value.children['describe 1'].children['describe 2'].specs['test spec']).toBeDefined();46 });47 it('should set fullDefinitionName on SpecBegin event', function() {48 runner.emit('SpecBegin', buildSpec(1, 'fake spec', ['describe 2']));49 var spec = model.getSpec(1);50 expect(spec.fullDefinitionName).toBeDefined();51 expect(spec.fullDefinitionName).toEqual('describe 2');52 });53 it('should set fullDefinitionName on SpecBegin event (join more names by space)', function() {54 runner.emit('SpecBegin', buildSpec(1, 'fake spec', ['describe 2', 'describe 1']));55 var spec = model.getSpec(1);56 expect(spec.fullDefinitionName).toEqual('describe 1 describe 2');57 });58 it('should add step to spec on StepBegin', function() {59 runner.emit('SpecBegin', spec);60 runner.emit('StepBegin', spec, step);61 runner.emit('StepEnd', spec, step);62 runner.emit('SpecEnd', spec);63 expect(model.value.children['describe 1'].specs['test spec'].steps.length).toEqual(1);64 });65 it('should update spec timer duration on SpecEnd event', function() {66 runner.emit('SpecBegin', spec);67 runner.emit('SpecEnd', spec);68 expect(model.value.children['describe 1'].specs['test spec'].duration).toBeDefined();69 });70 it('should update step timer duration on StepEnd event', function() {71 runner.emit('SpecBegin', spec);72 runner.emit('StepBegin', spec, step);73 runner.emit('StepEnd', spec, step);74 runner.emit('SpecEnd', spec);75 expect(model.value.children['describe 1'].specs['test spec'].steps[0].duration).toBeDefined();76 });77 it('should set spec status on SpecEnd to success if no status set', function() {78 runner.emit('SpecBegin', spec);79 runner.emit('SpecEnd', spec);80 expect(model.value.children['describe 1'].specs['test spec'].status).toEqual('success');81 });82 it('should set status to error after SpecError', function() {83 runner.emit('SpecBegin', spec);84 runner.emit('SpecError', spec, 'error');85 expect(model.value.children['describe 1'].specs['test spec'].status).toEqual('error');86 });87 it('should set spec status to failure if step fails', function() {88 runner.emit('SpecBegin', spec);89 runner.emit('StepBegin', spec, step);90 runner.emit('StepEnd', spec, step);91 runner.emit('StepBegin', spec, step);92 runner.emit('StepFailure', spec, step, 'error');93 runner.emit('StepEnd', spec, step);94 runner.emit('StepBegin', spec, step);95 runner.emit('StepEnd', spec, step);96 runner.emit('SpecEnd', spec);97 expect(model.value.children['describe 1'].specs['test spec'].status).toEqual('failure');98 });99 it('should set spec status to error if step errors', function() {100 runner.emit('SpecBegin', spec);101 runner.emit('StepBegin', spec, step);102 runner.emit('StepError', spec, step, 'error');103 runner.emit('StepEnd', spec, step);104 runner.emit('StepBegin', spec, step);105 runner.emit('StepFailure', spec, step, 'error');106 runner.emit('StepEnd', spec, step);107 runner.emit('SpecEnd', spec);108 expect(model.value.children['describe 1'].specs['test spec'].status).toEqual('error');109 });110 describe('events', function() {111 var Spec = angular.scenario.ObjectModel.Spec,112 Step = angular.scenario.ObjectModel.Step,113 callback;114 beforeEach(function() {115 callback = jasmine.createSpy('listener');116 });117 it('should provide method for registering a listener', function() {118 expect(model.on).toBeDefined();119 expect(model.on instanceof Function).toBe(true);120 });121 it('should forward SpecBegin event', function() {122 model.on('SpecBegin', callback);123 runner.emit('SpecBegin', spec);124 expect(callback).toHaveBeenCalled();125 });126 it('should forward SpecBegin event with ObjectModel.Spec as a param', function() {127 model.on('SpecBegin', callback);128 runner.emit('SpecBegin', spec);129 expect(callback.mostRecentCall.args[0] instanceof Spec).toBe(true);130 expect(callback.mostRecentCall.args[0].name).toEqual(spec.name);131 });132 it('should forward SpecError event', function() {133 model.on('SpecError', callback);134 runner.emit('SpecBegin', spec);135 runner.emit('SpecError', spec, {});136 expect(callback).toHaveBeenCalled();137 });138 it('should forward SpecError event with ObjectModel.Spec and error as a params', function() {139 var error = {};140 model.on('SpecError', callback);141 runner.emit('SpecBegin', spec);142 runner.emit('SpecError', spec, error);143 var param = callback.mostRecentCall.args[0];144 expect(param instanceof Spec).toBe(true);145 expect(param.name).toEqual(spec.name);146 expect(param.status).toEqual('error');147 expect(param.error).toBe(error);148 });149 it('should forward SpecEnd event', function() {150 model.on('SpecEnd', callback);151 runner.emit('SpecBegin', spec);152 runner.emit('SpecEnd', spec);153 expect(callback).toHaveBeenCalled();154 });155 it('should forward SpecEnd event with ObjectModel.Spec as a param', function() {156 model.on('SpecEnd', callback);157 runner.emit('SpecBegin', spec);158 runner.emit('SpecEnd', spec);159 expect(callback.mostRecentCall.args[0] instanceof Spec).toBe(true);160 expect(callback.mostRecentCall.args[0].name).toEqual(spec.name);161 });162 it('should forward StepBegin event', function() {163 model.on('StepBegin', callback);164 runner.emit('SpecBegin', spec);165 runner.emit('StepBegin', spec, step);166 expect(callback).toHaveBeenCalled();167 });168 it('should forward StepBegin event with Spec and Step as params', function() {169 model.on('StepBegin', callback);170 runner.emit('SpecBegin', spec);171 runner.emit('StepBegin', spec, step);172 var params = callback.mostRecentCall.args;173 expect(params[0] instanceof Spec).toBe(true);174 expect(params[0].name).toEqual(spec.name);175 expect(params[1] instanceof Step).toBe(true);176 });177 it('should forward StepError event', function() {178 model.on('StepError', callback);179 runner.emit('SpecBegin', spec);180 runner.emit('StepBegin', spec, step);181 runner.emit('StepError', spec, step, {});182 expect(callback).toHaveBeenCalled();183 });184 it('should forward StepError event with Spec, Step and error as params', function() {185 var error = {};186 model.on('StepError', callback);187 runner.emit('SpecBegin', spec);188 runner.emit('StepBegin', spec, step);189 runner.emit('StepError', spec, step, error);190 var params = callback.mostRecentCall.args;191 expect(params[0] instanceof Spec).toBe(true);192 expect(params[0].name).toEqual(spec.name);193 expect(params[1] instanceof Step).toBe(true);194 expect(params[1].status).toEqual('error');195 expect(params[2]).toBe(error);196 });197 it('should forward StepFailure event', function() {198 model.on('StepFailure', callback);199 runner.emit('SpecBegin', spec);200 runner.emit('StepBegin', spec, step);201 runner.emit('StepFailure', spec, step, {});202 expect(callback).toHaveBeenCalled();203 });204 it('should forward StepFailure event with Spec, Step and error as params', function() {205 var error = {};206 model.on('StepFailure', callback);207 runner.emit('SpecBegin', spec);208 runner.emit('StepBegin', spec, step);209 runner.emit('StepFailure', spec, step, error);210 var params = callback.mostRecentCall.args;211 expect(params[0] instanceof Spec).toBe(true);212 expect(params[0].name).toEqual(spec.name);213 expect(params[1] instanceof Step).toBe(true);214 expect(params[1].status).toEqual('failure');215 expect(params[2]).toBe(error);216 });217 it('should forward StepEnd event', function() {218 model.on('StepEnd', callback);219 runner.emit('SpecBegin', spec);220 runner.emit('StepBegin', spec, step);221 runner.emit('StepEnd', spec, step);222 expect(callback).toHaveBeenCalled();223 });224 it('should forward StepEnd event with Spec and Step as params', function() {225 model.on('StepEnd', callback);226 runner.emit('SpecBegin', spec);227 runner.emit('StepBegin', spec, step);228 runner.emit('StepEnd', spec, step);229 var params = callback.mostRecentCall.args;230 expect(params[0] instanceof Spec).toBe(true);231 expect(params[0].name).toEqual(spec.name);232 expect(params[1] instanceof Step).toBe(true);233 });234 it('should forward RunnerEnd event', function() {235 model.on('RunnerEnd', callback);236 runner.emit('RunnerEnd');237 expect(callback).toHaveBeenCalled();238 });239 it('should set error of first failure', function() {240 var error = 'first-error',241 step2 = buildStep();242 model.on('SpecEnd', function(spec) {243 expect(spec.error).toBeDefined();244 expect(spec.error).toBe(error);245 });246 runner.emit('SpecBegin', spec);247 runner.emit('StepBegin', spec, step);248 runner.emit('StepFailure', spec, step, error);249 runner.emit('StepBegin', spec, step2);250 runner.emit('StepFailure', spec, step2, 'second-error');251 runner.emit('SpecEnd', spec);252 });253 it('should set line number of first failure', function() {254 var step = buildStep('fake', 'first-line'),255 step2 = buildStep('fake2', 'second-line');256 model.on('SpecEnd', function(spec) {257 expect(spec.line).toBeDefined();258 expect(spec.line).toBe('first-line');259 });260 runner.emit('SpecBegin', spec);261 runner.emit('StepBegin', spec, step);262 runner.emit('StepFailure', spec, step, null);263 runner.emit('StepBegin', spec, step2);264 runner.emit('StepFailure', spec, step2, null);265 runner.emit('SpecEnd', spec);266 });267 });...
app.js
Source:app.js
...23 ID[username]=id;24 socket.roomid=roomid;25 room[username]=roomid;26 socket.join(roomid);27 socket.emit('notify','You have joined chatroom ' +roomid);28 socket.broadcast.to(socket.roomid).emit('notify',socket.username+' have connected!');29 var local={};30 for(people in Userlist){31 if(room[people]==socket.roomid) local[people]=people;32 }33 io.to(socket.roomid).emit('update',local);34 io.emit('online-update',Userlist);35 io.emit('select',Userlist,socket.username);36 })37 socket.on('sendmes',function(data){38 io.to(socket.roomid).emit('post',socket.username," "+data);39 })40 //disconnect-api41 socket.on('leave-room',function(roomid){42 socket.leave(socket.roomid);43 socket.emit('disconnect');44 socket.roomid=roomid;45 room[socket.username]=socket.roomid;46 Userlist[socket.username]=socket.username;47 socket.join(roomid);48 socket.emit('notify','You have joined chatroom ' +roomid);49 socket.broadcast.to(socket.roomid).emit('notify',socket.username+' have connected!');50 var local={};51 for(people in Userlist){52 if(room[people]==socket.roomid) local[people]=people;53 }54 io.to(socket.roomid).emit('update',local);55 io.emit('online-update',Userlist);56 })57 socket.on('disconnect',function(){58 delete Userlist[socket.username];59 delete room[socket.username];60 io.to(socket.roomid).emit('leave',socket.username+' has left');61 var local={};62 for(people in Userlist){63 if(room[people]==socket.roomid) local[people]=people;64 }65 io.to(socket.roomid).emit('update',local);66 io.emit('online-update',Userlist);67 })68 //private-message-api69 socket.on('private',function(data,id){70 var receive='To '+id;71 var sender ='From '+socket.username;72 socket.emit('post-private',receive,data);73 io.to(ID[id]).emit('post-private',sender,data);74 })75 //add chat member76 socket.on('addchatmember',function(invited,roomname,caller){77 socket.to(ID[invited]).emit('invite',roomname,caller);78 })79 socket.on('refuse',function(caller,refuse_name){80 socket.to(ID[caller]).emit('refused',refuse_name);81 })82 //videocall-api83 socket.on('peer-id',function(data){84 socket.peerid=data;85 })86 socket.on('change-type-private',function(des){87 socket.to(ID[des]).emit('change-type-1');88 })89 socket.on('request',function(calling,stream){90 socket.to(ID[calling]).emit('response',socket.username);91 })92 socket.on('accept',function(data,name){93 socket.to(ID[name]).emit('ok',data);94 })95 socket.on('busy',function(name){96 socket.to(ID[name]).emit('alr-busy');97 })98 socket.on('deny',function(name){99 socket.to(ID[name]).emit('not-ok');100 })101 //change-name-api102 socket.on('change-name',function(newname){103 for(name in Userlist){104 if(name==newname){105 socket.emit('name-invalid');106 return;107 }108 }109 var oldname=socket.username;110 delete Userlist[oldname];111 Userlist[newname]=newname;112 ID[newname]=ID[oldname];113 delete ID[oldname];114 room[newname]=room[oldname];115 delete room[oldname];116 socket.username=newname;117 socket.join(room[newname]);118 socket.emit('notify','You have joined chatroom ' +socket.roomid);119 socket.broadcast.to(socket.roomid).emit('notify',socket.username+' have connected!');120 var local={};121 for(people in Userlist){122 if(room[people]==socket.roomid) local[people]=people;123 }124 io.to(socket.roomid).emit('update',local);125 io.emit('online-update',Userlist);126 io.emit('select',Userlist);127 })128 //a person is typing129 socket.on('typing',function(data,name){130 socket.broadcast.to(socket.roomid).emit('noti-type',data,name);131 })132 socket.on('stop-typing',function(name){133 socket.broadcast.to(socket.roomid).emit('unnoti-type',name);134 })135 //group-video-call-api136 socket.on('group-request',function(list,name){137 socket.to(ID[name]).emit('group-response',list,socket.username);138 })139 socket.on('list-update',function(list,host,name){140 socket.to(ID[host]).emit('host-update',list,name);141 })142 socket.on('member-update',function(memberlist,peerlist){143 for(var index=0;index<memberlist.length;index++){144 socket.to(ID[memberlist[index]]).emit('mem-update',peerlist,memberlist);145 }146 })147 socket.on('group-busy',function(name){148 socket.to(ID[name]).emit('group-alr-busy');149 })150 socket.on('endcall',function(member,id){151 for(var index=0;index<member.length;index++){152 socket.to(ID[member[index]]).emit('closed',member,id);153 }154 })155 socket.on('change-type-group',function(des){156 socket.to(ID[des]).emit('change-type-2');157 })158 //img share159 socket.on('upload',function(data,sender){160 var guess = data.base64.match(/^data:image\/(png|jpeg);base64,/)[1];161 var ext = "";162 switch(guess) {163 case "png" : ext = ".png"; break;164 case "jpeg" : ext = ".jpg"; break;165 default : ext = ".bin"; break;166 }167 var savedFilename = "/upload/"+randomString()+ext;168 fs.writeFile(__dirname+"/public"+savedFilename, getBase64Image(data.base64), 'base64', function(err) {169 if (err !== null)170 console.log(err);171 else172 io.to(socket.roomid).emit('img-share', {path: savedFilename,},sender);173 });174 175 })176})177http.listen(process.env.PORT||3000,function(){178 console.log('Sever is running on port '+3000);179})180function getBase64Image(imgData) {181 return imgData.replace(/^data:image\/(png|jpeg|jpg);base64,/, "");182}183function randomString(){184 return num=Math.floor(Math.random() * 100000).toString();185}186function cleanUpload(){...
events.js
Source:events.js
...24 $element.off(event, childSelector);25 };26 // Close the channel since the element doesn't exist.27 if (!$element.length) {28 emit(END);29 return unsubscribe;30 }31 // Setup the subscription.32 $element.onFirst(event, childSelector, (event) => {33 handler(emit, $element, event);34 });35 // Emit the initial value.36 handler(emit, $element);37 return unsubscribe;38 }, buffers.fixed(1));39}40/**41 * Create a channel that will listen for `change` events on selectbox.42 *43 * @param {String} selector44 * @return {Object}45 */46export function createSelectboxChannel(selector) {47 return createChannel(selector, 'change', function(emit, $element) {48 emit({49 value: $element.val(),50 option: $element.find(':selected').first().get(0),51 });52 });53}54/**55 * Create a channel that will listen for `change` events on radio/checkbox inputs.56 *57 * @param {String} selector58 * @return {Object}59 */60export function createCheckableChannel(selector) {61 return createChannel(selector, 'change', (emit, $element) => {62 const elements = $element.find('input:checked').get();63 const values = elements.map(element => element.value);64 emit({65 values,66 elements,67 });68 }, 'input');69}70/**71 * Create a channel that will listen for `change` events on text fields.72 *73 * @param {String} selector74 * @return {Object}75 */76export function createTextChangeChannel(selector) {77 return createChannel(selector, 'change', (emit, $element) => {78 const value = $element.val();79 emit({80 value,81 });82 });83}84/**85 * Create a channel that will listen for `scroll` events.86 *87 * @param {String} selector88 * @return {Object}89 */90export function createScrollChannel(selector) {91 return createChannel(selector, 'scroll', (emit, $element) => {92 emit({93 value: $element.scrollTop()94 });95 });96}97/**98 * Create a channel that will listen for `submit` events.99 *100 * @param {String} selector101 * @param {String} [childSelector]102 * @return {Object}103 */104export function createSubmitChannel(selector, childSelector = null) {105 return createChannel(selector, 'submit', (emit, $element, event) => {106 if (event) {107 emit({108 event,109 });110 }111 }, childSelector);112}113/**114 * Create a channel that will listen for `click` events.115 *116 * @param {String} selector117 * @param {String} [childSelector]118 * @return {Object}119 */120export function createClickChannel(selector, childSelector = null) {121 return createChannel(selector, 'click', (emit, $element, event) => {122 if (event) {123 emit({124 event,125 });126 }127 }, childSelector);128}129/**130 * Create a channel for interaction with the media browser of WordPress.131 *132 * @param {Object} settings133 * @return {Object}134 */135export function createMediaBrowserChannel(settings) {136 return eventChannel((emit) => {137 // Create a new instance of the media browser.138 const browser = window.wp.media(settings);139 let AttachmentLibrary = wp.media.view.Attachment.Library;140 window.wp.media.view.Attachment.Library = AttachmentLibrary.extend({141 render: function () {142 let {143 controller: { options: { selected } }144 } = this;145 selected = isArray(selected) ? selected : [ selected ];146 selected = selected.map(id => parseInt(id, 10));147 const {148 id149 } = this.model;150 if (selected && selected.indexOf(id) !== -1) {151 this.$el.addClass('carbon-selected');152 } else {153 this.$el.removeClass('carbon-selected');154 }155 return AttachmentLibrary.prototype.render.apply( this, arguments );156 },157 });158 // Emit the selection through the channel.159 const onSelect = () => {160 emit({161 selection: browser.state().get('selection').toJSON(),162 });163 };164 // Emit the closing modal through the channel.165 const onClose = () => {166 emit({167 closed: true168 });169 };170 // Cancel the subscription.171 const unsubscribe = () => {172 browser.off('select', onSelect);173 browser.off('close', onClose);174 browser.remove();175 };176 // Setup the subscription.177 browser.on('select', onSelect);178 browser.on('close', onClose);179 // Emit the instance of browser so it can be used by subscribers.180 emit({181 browser,182 });183 return unsubscribe;184 }, buffers.fixed(1));185}186/**187 * Create a channel that will intercept all occurences188 * of the specified AJAX action.189 *190 * @param {String} event191 * @param {String} action192 * @return {Object}193 */194export function createAjaxChannel(event, action) {195 return eventChannel((emit) => {196 // Emit the AJAX event through the channel.197 const handler = (event, xhr, settings, data) => {198 if (isString(settings.data) && settings.data.indexOf(action) > -1) {199 emit({200 event,201 xhr,202 settings,203 data,204 });205 }206 };207 // Cancel the subscription.208 const unsubscribe = () => {209 $(document).off(event, handler);210 };211 // Setup the subscription.212 $(document).on(event, handler);213 return unsubscribe;214 }, buffers.fixed(1));215}216/**217 * Create a channel that will intercept all `widget-added` & `widget-updated` events218 * from `Widgets` page.219 *220 * @return {Object}221 */222export function createWidgetsChannel() {223 return eventChannel((emit) => {224 // Emit the event through the channel.225 const handler = (event, widget) => {226 emit({227 event,228 widget,229 });230 };231 // Cancel the subscription.232 const unsubscribe = () => {233 $(document).off('widget-before-added widget-added widget-updated', handler);234 };235 // Setup the subscription.236 $(document).on('widget-before-added widget-added widget-updated', handler);237 return unsubscribe;238 }, buffers.fixed(1));...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!