How to use setFile method in qawolf

Best JavaScript code snippet using qawolf

Scope.spec.ts

Source:Scope.spec.ts Github

copy

Full Screen

...25 sinon.restore();26 program.dispose();27 });28 it('does not mark namespace functions as collisions with stdlib', () => {29 program.setFile({30 src: `${rootDir}/source/main.bs`,31 dest: `source/main.bs`32 }, `33 namespace a34 function constructor()35 end function36 end namespace37 `);38 program.validate();39 expectZeroDiagnostics(program);40 });41 it('handles variables with javascript prototype names', () => {42 program.setFile('source/main.brs', `43 sub main()44 constructor = true45 end sub46 `);47 program.validate();48 expectZeroDiagnostics(program);49 });50 it('flags parameter with same name as namespace', () => {51 program.setFile('source/main.bs', `52 namespace NameA.NameB53 end namespace54 sub main(nameA)55 end sub56 `);57 program.validate();58 expectDiagnostics(program, [59 DiagnosticMessages.parameterMayNotHaveSameNameAsNamespace('nameA')60 ]);61 });62 it('flags assignments with same name as namespace', () => {63 program.setFile('source/main.bs', `64 namespace NameA.NameB65 end namespace66 sub main()67 namea = 268 NAMEA += 169 end sub70 `);71 program.validate();72 expectDiagnostics(program, [73 DiagnosticMessages.variableMayNotHaveSameNameAsNamespace('namea'),74 DiagnosticMessages.variableMayNotHaveSameNameAsNamespace('NAMEA')75 ]);76 });77 it('allows adding diagnostics', () => {78 const source = program.getScopeByName('source');79 const expected = [{80 message: 'message',81 file: undefined,82 range: undefined83 }];84 source.addDiagnostics(expected);85 expectDiagnostics(source, expected);86 });87 it('allows getting all scopes', () => {88 const scopes = program.getScopes();89 expect(scopes.length).to.equal(2);90 });91 describe('addFile', () => {92 it('detects callables from all loaded files', () => {93 const sourceScope = program.getScopeByName('source');94 program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `95 sub Main()96 end sub97 sub ActionA()98 end sub99 `);100 program.setFile({ src: s`${rootDir}/source/lib.brs`, dest: s`source/lib.brs` }, `101 sub ActionB()102 end sub103 `);104 program.validate();105 expect(sourceScope.getOwnFiles().map(x => x.srcPath).sort()).eql([106 s`${rootDir}/source/lib.brs`,107 s`${rootDir}/source/main.brs`108 ]);109 expectZeroDiagnostics(program);110 expect(sourceScope.getOwnCallables()).is.lengthOf(3);111 expect(sourceScope.getAllCallables()).is.length.greaterThan(3);112 });113 it('picks up new callables', () => {114 program.setFile('source/file.brs', '');115 //we have global callables, so get that initial number116 let originalLength = program.getScopeByName('source').getAllCallables().length;117 program.setFile('source/file.brs', `118 function DoA()119 print "A"120 end function121 function DoA()122 print "A"123 end function124 `);125 expect(program.getScopeByName('source').getAllCallables().length).to.equal(originalLength + 2);126 });127 });128 describe('removeFile', () => {129 it('removes callables from list', () => {130 //add the file131 let file = program.setFile(`source/file.brs`, `132 function DoA()133 print "A"134 end function135 `);136 let initCallableCount = program.getScopeByName('source').getAllCallables().length;137 //remove the file138 program.removeFile(file.srcPath);139 expect(program.getScopeByName('source').getAllCallables().length).to.equal(initCallableCount - 1);140 });141 });142 describe('validate', () => {143 describe('createObject', () => {144 it('recognizes various scenegraph nodes', () => {145 program.setFile(`source/file.brs`, `146 sub main()147 scene = CreateObject("roSGScreen")148 button = CreateObject("roSGNode", "Button")149 list = CreateObject("roSGNode", "MarkupList")150 end sub151 `);152 program.validate();153 expectZeroDiagnostics(program);154 });155 it('recognizes valid custom components', () => {156 program.setFile('components/comp1.xml', trim`157 <?xml version="1.0" encoding="utf-8" ?>158 <component name="Comp1" extends="Scene">159 </component>160 `);161 program.setFile('components/comp2.xml', trim`162 <?xml version="1.0" encoding="utf-8" ?>163 <component name="Comp2" extends="Scene">164 </component>165 `);166 program.setFile(`source/file.brs`, `167 sub main()168 comp1 = CreateObject("roSGNode", "Comp1")169 comp2 = CreateObject("roSGNode", "Comp2")170 end sub171 `);172 program.validate();173 expectZeroDiagnostics(program);174 });175 it('catches unknown roSGNodes', () => {176 program.setFile(`source/file.brs`, `177 sub main()178 scene = CreateObject("roSGNode", "notReal")179 button = CreateObject("roSGNode", "alsoNotReal")180 list = CreateObject("roSGNode", "definitelyNotReal")181 end sub182 `);183 program.validate();184 expectDiagnostics(program, [185 DiagnosticMessages.unknownRoSGNode('notReal'),186 DiagnosticMessages.unknownRoSGNode('alsoNotReal'),187 DiagnosticMessages.unknownRoSGNode('definitelyNotReal')188 ]);189 });190 it('only adds a single diagnostic when the file is used in multiple scopes', () => {191 program.setFile('components/Comp1.xml', trim`192 <?xml version="1.0" encoding="utf-8" ?>193 <component name="Comp1" extends="Scene">194 <script type="text/brightscript" uri="lib.brs" />195 </component>196 `);197 program.setFile('components/Comp2.xml', trim`198 <?xml version="1.0" encoding="utf-8" ?>199 <component name="Comp2" extends="Scene">200 <script type="text/brightscript" uri="lib.brs" />201 </component>202 `);203 program.setFile('components/lib.brs', `204 sub init()205 'unknown BrightScript component206 createObject("roDateTime_FAKE")207 'Wrong number of params208 createObject("roDateTime", "this param should not be here")209 'unknown roSGNode210 createObject("roSGNode", "Rectangle_FAKE")211 'deprecated212 fontMetrics = CreateObject("roFontMetrics", "someFontName")213 end sub214 `);215 program.validate();216 expectDiagnostics(program, [217 DiagnosticMessages.unknownBrightScriptComponent('roDateTime_FAKE'),218 DiagnosticMessages.mismatchCreateObjectArgumentCount('roDateTime', [1, 1], 2),219 DiagnosticMessages.unknownRoSGNode('Rectangle_FAKE'),220 DiagnosticMessages.deprecatedBrightScriptComponent('roFontMetrics').code221 ]);222 });223 it('disregards component library components', () => {224 program.setFile(`source/file.brs`, `225 sub main()226 scene = CreateObject("roSGNode", "Complib1:MainScene")227 button = CreateObject("roSGNode", "buttonlib:Button")228 list = CreateObject("roSGNode", "listlib:List")229 end sub230 `);231 program.validate();232 expectZeroDiagnostics(program);233 });234 it('disregards non-literal args', () => {235 program.setFile(`source/file.brs`, `236 sub main()237 sgNodeName = "roSGNode"238 compNameAsVar = "Button"239 button = CreateObject(sgNodeName, compNameAsVar)240 end sub241 `);242 program.validate();243 expectZeroDiagnostics(program);244 });245 it('recognizes valid BrightScript components', () => {246 program.setFile(`source/file.brs`, `247 sub main()248 timeSpan = CreateObject("roTimespan")249 bitmap = CreateObject("roBitmap", {width:10, height:10, AlphaEnable:false, name:"MyBitmapName"})250 path = CreateObject("roPath", "ext1:/vid")251 region = CreateObject("roRegion", bitmap, 20, 30, 100, 200)252 end sub253 `);254 program.validate();255 expectZeroDiagnostics(program);256 });257 it('catches invalid BrightScript components', () => {258 program.setFile(`source/file.brs`, `259 sub main()260 timeSpan = CreateObject("Thing")261 bitmap = CreateObject("OtherThing", {width:10, height:10, AlphaEnable:false, name:"MyBitmapName"})262 path = CreateObject("SomethingElse", "ext1:/vid")263 region = CreateObject("Button", bitmap, 20, 30, 100, 200)264 end sub265 `);266 program.validate();267 expectDiagnostics(program, [268 DiagnosticMessages.unknownBrightScriptComponent('Thing'),269 DiagnosticMessages.unknownBrightScriptComponent('OtherThing'),270 DiagnosticMessages.unknownBrightScriptComponent('SomethingElse'),271 DiagnosticMessages.unknownBrightScriptComponent('Button')272 ]);273 });274 it('catches wrong number of arguments', () => {275 program.setFile(`source/file.brs`, `276 sub main()277 button = CreateObject("roSGNode", "Button", "extraArg")278 bitmap = CreateObject("roBitmap") ' no 2nd arg279 timeSpan = CreateObject("roTimespan", 1, 2, 3)280 region = CreateObject("roRegion", bitmap, 20, 30, 100) ' missing last arg281 end sub282 `);283 program.validate();284 expectDiagnostics(program, [285 DiagnosticMessages.mismatchCreateObjectArgumentCount('roSGNode', [2], 3),286 DiagnosticMessages.mismatchCreateObjectArgumentCount('roBitmap', [2], 1),287 DiagnosticMessages.mismatchCreateObjectArgumentCount('roTimespan', [1], 4),288 DiagnosticMessages.mismatchCreateObjectArgumentCount('roRegion', [6], 5)289 ]);290 });291 it('catches deprecated components', () => {292 program.setFile(`source/file.brs`, `293 sub main()294 fontMetrics = CreateObject("roFontMetrics", "someFontName")295 end sub296 `);297 program.validate();298 // only care about code and `roFontMetrics` match299 const diagnostics = program.getDiagnostics();300 const expectedDiag = DiagnosticMessages.deprecatedBrightScriptComponent('roFontMetrics');301 expect(diagnostics.length).to.eql(1);302 expect(diagnostics[0].code).to.eql(expectedDiag.code);303 expect(diagnostics[0].message).to.contain(expectedDiag.message);304 });305 });306 it('marks the scope as validated after validation has occurred', () => {307 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `308 sub main()309 end sub310 `);311 let lib = program.setFile({ src: s`${rootDir}/source/lib.bs`, dest: s`source/lib.bs` }, `312 sub libFunc()313 end sub314 `);315 expect(program.getScopesForFile(lib)[0].isValidated).to.be.false;316 program.validate();317 expect(program.getScopesForFile(lib)[0].isValidated).to.be.true;318 lib = program.setFile({ src: s`${rootDir}/source/lib.bs`, dest: s`source/lib.bs` }, `319 sub libFunc()320 end sub321 `);322 //scope gets marked as invalidated323 expect(program.getScopesForFile(lib)[0].isValidated).to.be.false;324 });325 it('does not mark same-named-functions in different namespaces as an error', () => {326 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `327 namespace NameA328 sub alert()329 end sub330 end namespace331 namespace NameB332 sub alert()333 end sub334 end namespace335 `);336 program.validate();337 expectZeroDiagnostics(program);338 });339 it('resolves local-variable function calls', () => {340 program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `341 sub DoSomething()342 sayMyName = function(name as string)343 end function344 sayMyName()345 end sub`346 );347 program.validate();348 expectZeroDiagnostics(program);349 });350 describe('function shadowing', () => {351 it('warns when local var function has same name as stdlib function', () => {352 program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `353 sub main()354 str = function(p)355 return "override"356 end function357 print str(12345) 'prints "12345" (i.e. our local function is never used)358 end sub359 `);360 program.validate();361 expectDiagnostics(program, [{362 ...DiagnosticMessages.localVarFunctionShadowsParentFunction('stdlib'),363 range: Range.create(2, 24, 2, 27)364 }]);365 });366 it('warns when local var has same name as built-in function', () => {367 program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `368 sub main()369 str = 12345370 print str ' prints "12345" (i.e. our local variable is allowed to shadow the built-in function name)371 end sub372 `);373 program.validate();374 expectZeroDiagnostics(program);375 });376 it('warns when local var has same name as built-in function', () => {377 program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `378 sub main()379 str = 6789380 print str(12345) ' prints "12345" (i.e. our local variable did not override the callable global function)381 end sub382 `);383 program.validate();384 expectZeroDiagnostics(program);385 });386 it('detects local function with same name as scope function', () => {387 program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `388 sub main()389 getHello = function()390 return "override"391 end function392 print getHello() 'prints "hello" (i.e. our local variable is never called)393 end sub394 function getHello()395 return "hello"396 end function397 `);398 program.validate();399 expectDiagnostics(program, [{400 message: DiagnosticMessages.localVarFunctionShadowsParentFunction('scope').message,401 range: Range.create(2, 24, 2, 32)402 }]);403 });404 it('detects local function with same name as scope function', () => {405 program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `406 sub main()407 getHello = "override"408 print getHello ' prints <Function: gethello> (i.e. local variable override does NOT work for same-scope-defined methods)409 end sub410 function getHello()411 return "hello"412 end function413 `);414 program.validate();415 expectDiagnostics(program, [{416 message: DiagnosticMessages.localVarShadowedByScopedFunction().message,417 range: Range.create(2, 24, 2, 32)418 }]);419 });420 it('flags scope function with same name (but different case) as built-in function', () => {421 program.setFile({ src: s`${rootDir}/source/main.brs`, dest: s`source/main.brs` }, `422 sub main()423 print str(12345) ' prints 12345 (i.e. our str() function below is ignored)424 end sub425 function STR(num)426 return "override"427 end function428 `);429 program.validate();430 expectDiagnostics(program, [{431 message: DiagnosticMessages.scopeFunctionShadowedByBuiltInFunction().message,432 range: Range.create(4, 29, 4, 32)433 }]);434 });435 });436 it('detects duplicate callables', () => {437 program.setFile('source/file.brs', `438 function DoA()439 print "A"440 end function441 function DoA()442 print "A"443 end function444 `);445 expectZeroDiagnostics(program);446 //validate the scope447 program.validate();448 //we should have the "DoA declared more than once" error twice (one for each function named "DoA")449 expectDiagnostics(program, [450 DiagnosticMessages.duplicateFunctionImplementation('DoA', 'source'),451 DiagnosticMessages.duplicateFunctionImplementation('DoA', 'source')452 ]);453 });454 it('detects calls to unknown callables', () => {455 program.setFile('source/file.brs', `456 function DoA()457 DoB()458 end function459 `);460 expectZeroDiagnostics(program);461 //validate the scope462 program.validate();463 expectDiagnostics(program, [464 DiagnosticMessages.callToUnknownFunction('DoB', 'source')465 ]);466 });467 it('recognizes known callables', () => {468 program.setFile('source/file.brs', `469 function DoA()470 DoB()471 end function472 function DoB()473 DoC()474 end function475 `);476 //validate the scope477 program.validate();478 expectDiagnostics(program, [479 DiagnosticMessages.callToUnknownFunction('DoC', 'source')480 ]);481 });482 it('does not error with calls to callables in same namespace', () => {483 program.setFile('source/file.bs', `484 namespace Name.Space485 sub a(param as string)486 print param487 end sub488 sub b()489 a("hello")490 end sub491 end namespace492 `);493 //validate the scope494 program.validate();495 expectZeroDiagnostics(program);496 });497 //We don't currently support someObj.callSomething() format, so don't throw errors on those498 it('does not fail on object callables', () => {499 expectZeroDiagnostics(program);500 program.setFile('source/file.brs', `501 function DoB()502 m.doSomething()503 end function504 `);505 //validate the scope506 program.validate();507 //shouldn't have any errors508 expectZeroDiagnostics(program);509 });510 it('detects calling functions with too many parameters', () => {511 program.setFile('source/file.brs', `512 sub a()513 end sub514 sub b()515 a(1)516 end sub517 `);518 program.validate();519 expectDiagnostics(program, [520 DiagnosticMessages.mismatchArgumentCount(0, 1).message521 ]);522 });523 it('detects calling class constructors with too many parameters', () => {524 program.setFile('source/main.bs', `525 function noop0()526 end function527 function noop1(p1)528 end function529 sub main()530 noop0(1)531 noop1(1,2)532 noop1()533 end sub534 `);535 program.validate();536 expectDiagnostics(program, [537 DiagnosticMessages.mismatchArgumentCount(0, 1),538 DiagnosticMessages.mismatchArgumentCount(1, 2),539 DiagnosticMessages.mismatchArgumentCount(1, 0)540 ]);541 });542 it('detects calling functions with too many parameters', () => {543 program.setFile('source/file.brs', `544 sub a(name)545 end sub546 sub b()547 a()548 end sub549 `);550 program.validate();551 expectDiagnostics(program, [552 DiagnosticMessages.mismatchArgumentCount(1, 0)553 ]);554 });555 it('allows skipping optional parameter', () => {556 program.setFile('source/file.brs', `557 sub a(name="Bob")558 end sub559 sub b()560 a()561 end sub562 `);563 program.validate();564 //should have an error565 expectZeroDiagnostics(program);566 });567 it('shows expected parameter range in error message', () => {568 program.setFile('source/file.brs', `569 sub a(age, name="Bob")570 end sub571 sub b()572 a()573 end sub574 `);575 program.validate();576 //should have an error577 expectDiagnostics(program, [578 DiagnosticMessages.mismatchArgumentCount('1-2', 0)579 ]);580 });581 it('handles expressions as arguments to a function', () => {582 program.setFile('source/file.brs', `583 sub a(age, name="Bob")584 end sub585 sub b()586 a("cat" + "dog" + "mouse")587 end sub588 `);589 program.validate();590 expectZeroDiagnostics(program);591 });592 it('Catches extra arguments for expressions as arguments to a function', () => {593 program.setFile('source/file.brs', `594 sub a(age)595 end sub596 sub b()597 a(m.lib.movies[0], 1)598 end sub599 `);600 program.validate();601 //should have an error602 expectDiagnostics(program, [603 DiagnosticMessages.mismatchArgumentCount(1, 2)604 ]);605 });606 it('handles JavaScript reserved names', () => {607 program.setFile('source/file.brs', `608 sub constructor()609 end sub610 sub toString()611 end sub612 sub valueOf()613 end sub614 sub getPrototypeOf()615 end sub616 `);617 program.validate();618 expectZeroDiagnostics(program);619 });620 it('Emits validation events', () => {621 program.setFile('source/file.brs', ``);622 program.setFile('components/comp.xml', trim`623 <?xml version="1.0" encoding="utf-8" ?>624 <component name="comp" extends="Scene">625 <script uri="comp.brs"/>626 </component>627 `);628 program.setFile(s`components/comp.brs`, ``);629 const sourceScope = program.getScopeByName('source');630 const compScope = program.getScopeByName('components/comp.xml');631 program.plugins = new PluginInterface([], new Logger());632 const plugin = program.plugins.add({633 name: 'Emits validation events',634 beforeScopeValidate: sinon.spy(),635 onScopeValidate: sinon.spy(),636 afterScopeValidate: sinon.spy()637 });638 program.validate();639 const scopeNames = program.getScopes().map(x => x.name).filter(x => x !== 'global').sort();640 expect(plugin.beforeScopeValidate.callCount).to.equal(2);641 expect(plugin.beforeScopeValidate.calledWith(sourceScope)).to.be.true;642 expect(plugin.beforeScopeValidate.calledWith(compScope)).to.be.true;643 expect(plugin.onScopeValidate.callCount).to.equal(2);644 expect(plugin.onScopeValidate.getCalls().map(645 x => (x.args[0] as OnScopeValidateEvent).scope.name646 ).sort()).to.eql(scopeNames);647 expect(plugin.afterScopeValidate.callCount).to.equal(2);648 expect(plugin.afterScopeValidate.calledWith(sourceScope)).to.be.true;649 expect(plugin.afterScopeValidate.calledWith(compScope)).to.be.true;650 });651 describe('custom types', () => {652 it('detects an unknown function return type', () => {653 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `654 function a()655 return invalid656 end function657 function b() as integer658 return 1659 end function660 function c() as unknownType 'error661 return 2662 end function663 class myClass664 function myClassMethod() as unknownType 'error665 return 2666 end function667 end class668 function d() as myClass669 return new myClass()670 end function671 `);672 program.validate();673 expectDiagnostics(program, [674 DiagnosticMessages.invalidFunctionReturnType('unknownType').message,675 DiagnosticMessages.invalidFunctionReturnType('unknownType').message676 ]);677 });678 it('detects an unknown function parameter type', () => {679 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `680 sub a(num as integer)681 end sub682 sub b(unknownParam as unknownType) 'error683 end sub684 class myClass685 sub myClassMethod(unknownParam as unknownType) 'error686 end sub687 end class688 sub d(obj as myClass)689 end sub690 `);691 program.validate();692 expectDiagnostics(program, [693 DiagnosticMessages.functionParameterTypeIsInvalid('unknownParam', 'unknownType').message,694 DiagnosticMessages.functionParameterTypeIsInvalid('unknownParam', 'unknownType').message695 ]);696 });697 it('detects an unknown field parameter type', () => {698 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `699 class myClass700 foo as unknownType 'error701 end class702 class myOtherClass703 foo as unknownType 'error704 bar as myClass705 buz as myOtherClass706 end class707 `);708 program.validate();709 expectDiagnostics(program, [710 DiagnosticMessages.cannotFindType('unknownType').message,711 DiagnosticMessages.cannotFindType('unknownType').message712 ]);713 });714 it('supports enums and interfaces as types', () => {715 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `716 interface MyInterface717 title as string718 end interface719 enum myEnum720 title = "t"721 end enum722 class myClass723 foo as myInterface724 foo2 as myEnum725 end class726 `);727 program.validate();728 expectZeroDiagnostics(program);729 });730 it('finds interface types', () => {731 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `732 namespace MyNamespace733 interface MyInterface734 title as string735 end interface736 function bar(param as MyNamespace.MyInterface) as MyNamespace.MyInterface737 end function738 end namespace739 `);740 program.validate();741 expectZeroDiagnostics(program);742 });743 it('finds non-namespaced interface types', () => {744 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `745 interface MyInterface746 title as string747 end interface748 namespace MyNamespace749 function bar(param as MyInterface) as MyInterface750 end function751 end namespace752 `);753 program.validate();754 expectZeroDiagnostics(program);755 });756 it('finds enum types', () => {757 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `758 namespace MyNamespace759 enum MyEnum760 title = "t"761 end enum762 function bar(param as MyNamespace.MyEnum) as MyNamespace.MyEnum763 end function764 end namespace765 `);766 program.validate();767 expectZeroDiagnostics(program);768 });769 it('finds non-namespaced enum types', () => {770 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `771 enum MyEnum772 title = "t"773 end enum774 namespace MyNamespace775 function bar(param as MyEnum) as MyEnum776 end function777 end namespace778 `);779 program.validate();780 expectZeroDiagnostics(program);781 });782 it('finds custom types inside namespaces', () => {783 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `784 namespace MyNamespace785 class MyClass786 end class787 function foo(param as MyClass) as MyClass788 end function789 function bar(param as MyNamespace.MyClass) as MyNamespace.MyClass790 end function791 end namespace792 `);793 program.validate();794 expectZeroDiagnostics(program);795 });796 it('finds custom types from other namespaces', () => {797 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `798 namespace MyNamespace799 class MyClass800 end class801 end namespace802 function foo(param as MyNamespace.MyClass) as MyNamespace.MyClass803 end function804 `);805 program.validate();806 expectZeroDiagnostics(program);807 });808 it('detects missing custom types from current namespaces', () => {809 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `810 namespace MyNamespace811 class MyClass812 end class813 function foo() as UnknownType814 end function815 end namespace816 `);817 program.validate();818 expectDiagnostics(program, [819 DiagnosticMessages.invalidFunctionReturnType('UnknownType').message820 ]);821 });822 it('finds custom types from other other files', () => {823 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `824 function foo(param as MyClass) as MyClass825 end function826 `);827 program.setFile({ src: s`${rootDir}/source/MyClass.bs`, dest: s`source/MyClass.bs` }, `828 class MyClass829 end class830 `);831 program.validate();832 expectZeroDiagnostics(program);833 });834 it('finds custom types from other other files', () => {835 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `836 function foo(param as MyNameSpace.MyClass) as MyNameSpace.MyClass837 end function838 `);839 program.setFile({ src: s`${rootDir}/source/MyNameSpace.bs`, dest: s`source/MyNameSpace.bs` }, `840 namespace MyNameSpace841 class MyClass842 end class843 end namespace844 `);845 program.validate();846 expectZeroDiagnostics(program);847 });848 it('detects missing custom types from another namespaces', () => {849 program.setFile({ src: s`${rootDir}/source/main.bs`, dest: s`source/main.bs` }, `850 namespace MyNamespace851 class MyClass852 end class853 end namespace854 function foo() as MyNamespace.UnknownType855 end function856 `);857 program.validate();858 expectDiagnostics(program, [859 DiagnosticMessages.invalidFunctionReturnType('MyNamespace.UnknownType')860 ]);861 });862 it('scopes types to correct scope', () => {863 program = new Program({ rootDir: rootDir });864 program.setFile('components/foo.xml', trim`865 <?xml version="1.0" encoding="utf-8" ?>866 <component name="foo" extends="Scene">867 <script uri="foo.bs"/>868 </component>869 `);870 program.setFile(s`components/foo.bs`, `871 class MyClass872 end class873 `);874 program.validate();875 expectZeroDiagnostics(program);876 program.setFile('components/bar.xml', trim`877 <?xml version="1.0" encoding="utf-8" ?>878 <component name="bar" extends="Scene">879 <script uri="bar.bs"/>880 </component>881 `);882 program.setFile(s`components/bar.bs`, `883 function getFoo() as MyClass884 end function885 `);886 program.validate();887 expectDiagnostics(program, [888 DiagnosticMessages.invalidFunctionReturnType('MyClass').message889 ]);890 });891 it('can reference types from parent component', () => {892 program = new Program({ rootDir: rootDir });893 program.setFile('components/parent.xml', trim`894 <?xml version="1.0" encoding="utf-8" ?>895 <component name="parent" extends="Scene">896 <script uri="parent.bs"/>897 </component>898 `);899 program.setFile(s`components/parent.bs`, `900 class MyClass901 end class902 `);903 program.setFile('components/child.xml', trim`904 <?xml version="1.0" encoding="utf-8" ?>905 <component name="child" extends="parent">906 <script uri="child.bs"/>907 </component>908 `);909 program.setFile(s`components/child.bs`, `910 function getFoo() as MyClass911 end function912 `);913 program.validate();914 expectZeroDiagnostics(program);915 });916 });917 });918 describe('inheritance', () => {919 it('inherits callables from parent', () => {920 program = new Program({ rootDir: rootDir });921 program.setFile('components/child.xml', trim`922 <?xml version="1.0" encoding="utf-8" ?>923 <component name="child" extends="parent">924 <script uri="child.brs"/>925 </component>926 `);927 program.setFile(s`components/child.brs`, ``);928 program.validate();929 let childScope = program.getComponentScope('child');930 expect(childScope.getAllCallables().map(x => x.callable.name)).not.to.include('parentSub');931 program.setFile('components/parent.xml', trim`932 <?xml version="1.0" encoding="utf-8" ?>933 <component name="parent" extends="Scene">934 <script uri="parent.brs"/>935 </component>936 `);937 program.setFile(s`components/parent.brs`, `938 sub parentSub()939 end sub940 `);941 program.validate();942 expect(childScope.getAllCallables().map(x => x.callable.name)).to.include('parentSub');943 });944 });945 describe('detachParent', () => {946 it('does not attach global to itself', () => {947 expect(program.globalScope.getParentScope()).not.to.exist;948 });949 });950 describe('getDefinition', () => {951 it('returns empty list when there are no files', () => {952 let file = program.setFile({ src: `${rootDir}/source/main.brs`, dest: 'source/main.brs' }, '');953 let scope = program.getScopeByName('source');954 expect(scope.getDefinition(file, Position.create(0, 0))).to.be.lengthOf(0);955 });956 });957 describe('getCallablesAsCompletions', () => {958 it('returns documentation when possible', () => {959 let completions = program.globalScope.getCallablesAsCompletions(ParseMode.BrightScript);960 //it should find the completions for the global scope961 expect(completions).to.be.length.greaterThan(0);962 //it should find documentation for completions963 expect(completions.filter(x => !!x.documentation)).to.have.length.greaterThan(0);964 });965 });966 describe('buildNamespaceLookup', () => {967 it('does not crash when class statement is missing `name` prop', () => {968 program.setFile<BrsFile>('source/main.bs', `969 namespace NameA970 class971 end class972 end namespace973 `);974 program['scopes']['source'].buildNamespaceLookup();975 });976 it('does not crash when function statement is missing `name` prop', () => {977 const file = program.setFile<BrsFile>('source/main.bs', `978 namespace NameA979 function doSomething()980 end function981 end namespace982 `);983 delete ((file.ast.statements[0] as NamespaceStatement).body.statements[0] as FunctionStatement).name;984 program['scopes']['source'].buildNamespaceLookup();985 });986 });987 describe('buildEnumLookup', () => {988 it('builds enum lookup', () => {989 const sourceScope = program.getScopeByName('source');990 //eslint-disable-next-line @typescript-eslint/no-floating-promises991 program.setFile('source/main.bs', `992 enum foo993 bar1994 bar2995 end enum996 namespace test997 function fooFace2()998 end function999 class fooClass21000 end class1001 enum foo21002 bar2_11003 bar2_21004 end enum1005 end namespace...

Full Screen

Full Screen

setFile.js

Source:setFile.js Github

copy

Full Screen

1var setFile = {2 debug:false,3 idPerfix:"setFile",4 projectList:null,5 catId:null,6 tagList:[],7 fileTypeList:[],8 catList:null,9 csmsbwObj:null,10 saveData:{11 fileType: null,12 folder: null,13 name : null,14 description : null,15 fileSize : null,16 perviewImage: null,17 fileUrl: null,18 tagList : null,19 catList : null,20 projectList: null,21 action : null,22 format : 'json'23 }24};25setFile.RequestFile = function() {26 $.ajax({27 url: 'ws/GetFileList.php',28 type: 'POST',29 data: {30 format:'json',31 id:setFile.saveData.id32 },33 dataType: 'json',34 async: false,35 success: function(json) {36 var data = (json.WebService.FileList.File)[0];37 setFile.saveData.name = data.FileName;38 setFile.saveData.fileType = data.FileTypeId;39 setFile.saveData.perviewImage = data.PerviewImage;40 setFile.saveData.fileUrl = data.FileUrl;41 setFile.saveData.fileSize = data.FileSize;42 setFile.saveData.description = data.Description;43 setFile.saveData.catList = "";44 setFile.saveData.projectList = "";45 setFile.saveData.tagList = "";46 47 $.each(data.FileCatList.FileCat, function(index,cat) {48 setFile.saveData.catList+= (index < data.FileCatList.FileCat.length - 1)?cat.FileCatNodeId + ",":cat.FileCatNodeId;49 });50 51 $.each(data.ProjectList.Project, function(index,project) {52 setFile.saveData.projectList+= (index < data.ProjectList.Project.length - 1)?project.ProjectId + ",":project.ProjectId;53 });54 55 $.each(data.TagList.Tag, function(index,tag) {56 setFile.saveData.tagList+= (index < data.TagList.Tag.length - 1)?tag.TagId + ",":tag.TagId;57 });58 },59 error: function(XMLHttpRequest, textStatus, errorThrown) {60 BootstrapDialog.alert("访问GetFileList服务异常!" + XMLHttpRequest.responseText);61 }62 });63};64setFile.RequestProjectList = function() {65 $.ajax({66 url: 'ws/GetProjectList.php',67 type: 'POST',68 data:{69 format: 'json',70 pageSize: 99971 },72 dataType: 'json',73 async: false,74 success: function(json) {75 if(json.WebService.ProjectList){76 setFile.projectList = json.WebService.ProjectList.Project;77 }78 },79 error: function(XMLHttpRequest, textStatus, errorThrown) {80 BootstrapDialog.alert("访问GetProductList服务异常!" + XMLHttpRequest.responseText);81 }82 });83};84setFile.RequestCatList = function() {85 $.ajax({86 url: 'ws/GetFileCatList.php',87 type: 'POST',88 data:{89 format: 'json',90 catId: setFile.catId91 },92 dataType: 'json',93 async: false,94 success: function(json) {95 if(json.WebService.FileCatList){96 var catList = json.WebService.FileCatList.FileCat;97 setFile.catList = {"ItemList":setFile.SetSubMenuSelectBoxData(catList)};98 }99 },100 error: function(XMLHttpRequest, textStatus, errorThrown) {101 BootstrapDialog.alert("访问GetPaymentList服务异常!" + XMLHttpRequest.responseText);102 }103 });104};105setFile.SetSubMenuSelectBoxData = function(catList) {106 var result = [];107 $.each(catList, function(index,cat){108 var item = {ItemId:cat.FileCatNodeId, ItemName:cat.FileCatName, ParentId: cat.ParentCatId};109 if(cat.FileCatList){110 var subItem = setFile.SetSubMenuSelectBoxData(cat.FileCatList.FileCat);111 item.SubItem = subItem;112 }113 else114 item.Checked = "false";115 result.push(item);116 });117 return result;118};119setFile.RequestTagList = function() {120 $.ajax({121 url: 'ws/GetTagList.php',122 type: 'POST',123 data:{124 format: 'json'125 },126 dataType: 'json',127 async: false,128 success: function(json) {129 if(json.WebService.TagList){130 var tagList = json.WebService.TagList.Tag;131 setFile.tagList = [];132 $.each(tagList, function(index,tag) {133 setFile.tagList.push({"value":tag.TagId,"text":tag.TagName });134 });135 }136 },137 error: function(XMLHttpRequest, textStatus, errorThrown) {138 BootstrapDialog.alert("访问GetStoreList服务异常!" + XMLHttpRequest.responseText);139 }140 });141};142setFile.RequestFileType = function() {143 $.ajax({144 url: 'ws/GetFileType.php',145 type: 'POST',146 data:{147 format: 'json'148 },149 dataType: 'json',150 async: false,151 success: function(json) {152 if(json.WebService.FileTypeList){153 setFile.fileTypeList = json.WebService.FileTypeList.FileType;154 }155 },156 error: function(XMLHttpRequest, textStatus, errorThrown) {157 BootstrapDialog.alert("访问GetStoreList服务异常!" + XMLHttpRequest.responseText);158 }159 });160};161setFile.RequestSetFile = function() {162 $.ajax({163 url: 'ws/SetFile.php',164 type: 'POST',165 data: setFile.saveData,166 dataType: 'json',167 async: false,168 success: function(json) {169 if(json.WebService.Result > 0 && json.WebService.ResultCode === 200){170 var action = (setFile.saveData.action === "add")?"添加":"修改";171 172 BootstrapDialog.confirm({173 title: '提示',174 message: '保存成功,是否继续'+action+'?',175 closable: true, // <-- Default value is false176 draggable: true, // <-- Default value is false177 btnCancelLabel: '进入列表页', // <-- Default value is 'Cancel',178 btnOKLabel: '继续'+action, // <-- Default value is 'OK',179 btnOKClass: 'btn-primary', // <-- If you didn't specify it, dialog type will be used,180 callback: function(result) {181 // result will be true if button was click, while it will be false if users close the dialog directly.182 if(result) {183 if(setFile.saveData.action === "add")184 location.href="index.php?p=backend&c=File&a=add&catId="+setFile.catId+"&type="+setFile.saveData.fileType+"&folder="+setFile.saveData.folder;185 else if(setFile.saveData.action === "update")186 location.href="index.php?p=backend&c=File&a=update&catId="+setFile.catId+"&type="+setFile.saveData.fileType+"&folder="+setFile.saveData.folder+"&uid="+setFile.saveData.id;187 }else {188 location.href = "index.php?p=backend&c=File&a=list&catId="+setFile.catId+"&type="+setFile.saveData.fileType+"&folder="+setFile.saveData.folder;189 }190 }191 });192 }193 else{194 BootstrapDialog.alert(json.WebService.ResultMessage);195 }196 },197 error: function(XMLHttpRequest, textStatus, errorThrown) {198 BootstrapDialog.alert("访问SetFile服务异常!" + XMLHttpRequest.responseText);199 }200 });201};202setFile.DrawName = function() {203 if(setFile.debug) console.log("setFile.DrawName",setFile.saveData);204 var value = (setFile.saveData.name)?setFile.saveData.name:"";205 var params = {206 divId:"main-group",207 idPerfix: setFile.idPerfix+"-name",208 value:value,209 title:"文件名:",210 placeholder:'请输入文件名. e.g. 布艺双人沙发',211 type:"text",212 readonly:"",213 required:"required"214 };215 customTextWidget.Draw(params);216};217setFile.DrawDescription = function() {218 var value = (setFile.saveData.description)?setFile.saveData.description:"";219 var params = {220 divId:"main-group",221 idPerfix: setFile.idPerfix+"-description",222 title:"描述:",223 placeholder:'请输入备注. e.g. 带贴图',224 value:value225 };226 customTextareaWidget.Draw(params);227};228setFile.DrawPreviewImage = function() {229 if(setFile.debug) console.log("setFile.DrawImage",setFile.saveData.previewImage);230 var params = {231 divId:"main-group",232 idPrefix: setFile.idPerfix+"-previewImage",233 imageWidth: 250,234 imageHeight: 300,235 imageUrl:setFile.saveData.fileUrl,236 thumbnailImageUrl:setFile.saveData.perviewImage,237 fileSize:setFile.saveData.fileSize,238 title:"图片",239 helpText:" "240 };241 242 if(setFile.saveData.fileType == 2){243 params.onFinishCallBack = setFile.UploadFileOnFinishCB;244 }245 246 customImageWidget.Draw(params);247};248setFile.DrawUploadFile = function() {249 if(setFile.debug) console.log("setFile.DrawUploadFile",setFile.saveData.fileUrl);250 if(setFile.saveData.fileType == 1 || setFile.saveData.fileType == 3){251 var params = {252 divId:"main-group",253 idPrefix: setFile.idPerfix+"-fileUpload",254 fileUrl:setFile.saveData.fileUrl,255 fileSize: setFile.saveData.fileSize,256 title:"文件",257 onFinishCallBack:setFile.UploadFileOnFinishCB,258 helpText:" "259 };260 customFileUploadWidget.Draw(params);261 }262};263setFile.DrawProject = function() {264 if(setFile.debug) console.log("setFile.DrawProject",setFile.saveData);265 var selectedId = (setFile.saveData.projectList)?(setFile.saveData.projectList).split(","):"";266 var option = [];267 268 $.each(setFile.projectList, function(index,project) {269 var selected = 0;270 $.each(selectedId, function(index,projectId) {271 if(project.ProjectId === projectId)272 selected = 1;273 });274 option.push({name: project.ProjectName, id:project.ProjectId, selected: selected });275 });276 277 var params = {278 divId:"main-group",279 idPerfix: setFile.idPerfix+"-Project",280 placeholder: "",281 value:option,282 type: "multiple",283 title:"所属项目:<a onClick=\"projectDialog.AddProject()\">[添加]</a> <a onClick=\"projectDialog.EditProject()\">[修改]</a>"284 }; 285 customSelectBoxWidget.Draw(params);286};287setFile.DrawCat = function() {288 var selectedItemsId = null;289 if(setFile.saveData.catList){290 selectedItemsId = (setFile.saveData.catList).split(",");291 }292 293 var configSetting = {};294 configSetting.divId = "main-group";295 configSetting.title = "所属分类:<a onClick=\"fileCatDialog.AddFileCat()\">[添加]</a> <a onClick=\"fileCatDialog.EditFileCat()\">[修改]</a>";296 configSetting.selectData = setFile.catList;297 configSetting.selectedItemsId = (selectedItemsId)?selectedItemsId:"";298 if(setFile.csmsbwObj){ 299 setFile.csmsbwObj.ReDraw(configSetting); 300 }301 else{302 setFile.csmsbwObj = customSubMenuSelectBoxWidget.Create();303 setFile.csmsbwObj.Draw(configSetting);304 }305};306setFile.DrawTag = function() {307// var selectedData = [];308// if(setFile.saveData.tagList){309// var selectedTag = (setFile.saveData.tagList).split(",");310// $.each(setFile.tagList, function(index,tag) {311// $.each(selectedTag,function(selIndex,selTagId) {312// if(selTagId === tag.value){313// selectedData.push(tag);314// }315// });316// });317// }318 319 //var configSetting = {};320 //configSetting.divId = "main-group";321 //configSetting.title = "所属标签:";//<a onClick=\"tagDialog.AddTag()\">[添加可选标签]</a>322 //configSetting.url = 'ws/GetTagList.php?format=json';323 //configSetting.selectedData = selectedData;//{"value":1 ,"text": "木"}324 //setFile.csmtagsObj = customTagsGroup.Create();325 //setFile.csmtagsObj.Draw(configSetting);326 var option = [];327 $.each(setFile.tagList, function(index,tag) {328 var selected = 0;329 if(setFile.saveData.tagList){330 var selectedTag = (setFile.saveData.tagList).split(",");331 $.each(selectedTag, function(index,selTagId) {332 if(selTagId === tag.value){333 selected = 1;334 }335 });336 }337 option.push({name: tag.text, id:tag.value, selected: selected });338 });339 340 var params = {341 divId:"main-group",342 idPerfix: setFile.idPerfix+"-Tag",343 placeholder: "",344 value:option,345 type: "multiple",346 title:"所属标签:"347 }; 348 customSelectBoxWidget.Draw(params);349};350setFile.DrawSaveBtn = function() {351 var params = {352 divId:"main-group",353 idPerfix: setFile.idPerfix+"-saveBtn",354 value:"",355 title:"保存",356 readonly:""//readonly357 };358 359 var html = '<div class="form-group">'+360 '<div class="col-lg-offset-2 col-lg-10">'+361 '<button type="submit" class="btn btn-success pull-right" id="setFile-submit-btn" >'+params.title+'</button>'+362 '</div>'+363 '</div>';364 $("#"+params.divId).append(html);365 366 $("#main-group").submit(function(e){367 e.preventDefault();368 var disabled = $("#setFile-submit-btn").hasClass('disabled');369 if(!disabled){370 setFile.Save();371 }372 });373};374setFile.Save = function() {375 setFile.saveData.name = $("#setFile-name-inputText").val();376 setFile.saveData.perviewImage = $("#setFile-previewImage-image").attr("thumbnail");377 if(setFile.saveData.fileType == 1 || setFile.saveData.fileType == 3){378 setFile.saveData.fileUrl = $("#setFile-fileUpload-file").attr("val");379 setFile.saveData.fileSize = $('#setFile-fileUpload-file').attr("size");380 }381 else{382 setFile.saveData.fileUrl = $("#setFile-previewImage-image").attr("val");383 setFile.saveData.fileSize = $('#setFile-previewImage-image').attr("size");384 }385 setFile.saveData.description = $("#setFile-description-inputTextarea").val();386 setFile.saveData.projectList = ($("#setFile-Project-selectBox").val())?($("#setFile-Project-selectBox").val()).join():"";387 setFile.saveData.catList = setFile.csmsbwObj.GetSelectedItemId();388 setFile.saveData.tagList = ($("#setFile-Tag-selectBox").val())?($("#setFile-Tag-selectBox").val()).join():"";//setFile.csmtagsObj.GetSelectedData();389 390 var isPass = setFile.CheckSaveValue();391 if(isPass) setFile.RequestSetFile();392};393setFile.CheckSaveValue = function() {394 if(setFile.debug) console.log("setFile.Save",setFile.saveData);395 var errorMsg = "";396 if(setFile.saveData.perviewImage.length === 0){397 errorMsg = "请上传预览图";398 }399// if(setFile.saveData.projectList.length === 0){400// errorMsg = "请选择所属项目";401// }402 if(setFile.saveData.catList.length === 0){403 errorMsg = "请选择所属分类";404 }405 if(setFile.saveData.fileUrl.length === 0){406 errorMsg = "请上传文件";407 }408 if(errorMsg.length > 0){409 BootstrapDialog.alert(errorMsg);410 return false;411 }412 else{413 return true;414 }415};416$(document).ready(function () {417 setFile.RequestFileType();418 setFile.Init();419 setFile.RequestProjectList();420 setFile.RequestTagList();421 422 setFile.DrawName();423 setFile.DrawPreviewImage();424 setFile.DrawUploadFile();425 setFile.DrawDescription();426 setFile.DrawProject();427 setFile.DrawCat();428 setFile.DrawTag();429 setFile.DrawSaveBtn();430 431 $('#main-group').validator();432});433setFile.Init = function() {434 setFile.saveData.action = $.urlParams("get", "a");435 setFile.saveData.fileType = $.urlParams("get", "type");436 setFile.saveData.folder = $.urlParams("get", "folder");437 438 if(setFile.saveData.action === "update"){439 setFile.saveData.id = $.urlParams("get", "uid");440 setFile.RequestFile();441 }442 443 setFile.catId = $.urlParams("get", "catId");444 setFile.SetTitle();445 setFile.RequestCatList();446};447setFile.UploadFileOnFinishCB = function(data) {448 $.each(data, function (index, file) {449 var fileName = file.orgName;450 $("#setFile-name-inputText").val(fileName.substring(0,fileName.lastIndexOf(".")));451 setFile.saveData.name = file.name;452 });453};454setFile.SetTitle = function() {455 var title = "";456 var href = "index.php?p=backend&c=File&a=list&catId="+setFile.catId+"&type="+setFile.saveData.fileType+"&folder="+setFile.saveData.folder;457 458 $.each(setFile.fileTypeList,function(index,type) {459 if(type.FileTypeId == setFile.saveData.fileType){460 title = type.FileTypeName;461 return true;462 }463 });464 465 $("#setFile-nav-title").text(title);466 $("#setFile-nav-title").attr("href",href);467 468 if(setFile.saveData.action === "add"){469 title = "添加";470 }471 else if(setFile.saveData.action === "update"){472 title = "修改";473 }474 $("#setFile-title").text(title);...

Full Screen

Full Screen

util.js

Source:util.js Github

copy

Full Screen

...280 pwd = hg.state.computer.pwd,281 status = false;282 hg.state.makeDir("/tmp/setFile");283 hg.state.changeDir("/tmp/setFile");284 status = hg.util.setFile("/", "bla");285 strictEqual(status, null, "Cannot overwrite root.");286 ok(fs != "bla", "Double check root.");287 hg.state.computer.hasChanged = false;288 status = hg.util.setFile("/bin", "bla");289 strictEqual(status, null, "Cannot overwrite protected files (absolute path).");290 ok(fs.bin != "bla", "Double check /bin.");291 status = hg.util.setFile("../../bin", "bla");292 strictEqual(status, null, "Cannot overwrite protected files (relative path).");293 ok(fs.bin != "bla", "Triple check /bin.");294 // set on root295 status = hg.util.setFile("/setFile", "bla");296 strictEqual(status, true, "Seting a file on root.");297 strictEqual(fs.setFile, "bla", "Check new file on root.");298 ok(hg.state.computer.hasChanged, "State changed");299 hg.state.removeFile("/setFile");300 strictEqual(fs.setFile, undefined, "Removed file.");301 // set on nonexisting path302 status = hg.util.setFile("/tmp/setFile/hoho0/hoho1", {"bla": "bla"});303 strictEqual(status, false, "Seting a file on nonexistant path.");304 // set folder (abs)305 status = hg.util.setFile("/tmp/setFile/hoho1", {"bla": "bla"});306 strictEqual(status, true, "Seting a new dir on absolute path.");307 deepEqual(fs.tmp.setFile.hoho1, {"bla": "bla"}, "Check new dir on absolute path.");308 // set folder (rel)309 status = hg.util.setFile("hoho2", {"bla": "bla"});310 strictEqual(status, true, "Seting a new dir on relative path.");311 deepEqual(fs.tmp.setFile.hoho2, {"bla": "bla"}, "Check new dir on relative path.");312 strictEqual(fs.tmp.setFile.hoho2.bla, "bla", "Check file in new dir on relative path.");313 // set empty folder (rel)314 status = hg.util.setFile("../setFile/./hoho3", {});315 strictEqual(status, true, "Seting a new empty dir on relative path.");316 deepEqual(fs.tmp.setFile.hoho3, {}, "Check new empty dir on relative path.");317 // set binary (abs)318 status = hg.util.setFile("/tmp/setFile/bin1", null);319 strictEqual(status, true, "Seting binary on abs path.");320 strictEqual(fs.tmp.setFile.bin1, null, "Binary on abs path correct.");321 // set binary (rel)322 status = hg.util.setFile("bin2", null);323 strictEqual(status, true, "Seting binary on rel path.");324 strictEqual(fs.tmp.setFile.bin2, null, "Binary on rel path correct.");325 // set text (abs)326 status = hg.util.setFile("/tmp/setFile/txt1", "bla");327 strictEqual(status, true, "Seting text file on abs path.");328 strictEqual(fs.tmp.setFile.txt1, "bla", "Text file on abs path correct.");329 // set text (rel)330 status = hg.util.setFile("/tmp/setFile/txt2", "bla");331 strictEqual(status, true, "Seting text file on relative path.");332 strictEqual(fs.tmp.setFile.txt2, "bla", "Text file on relative path correct.");333 // check overwriting334 status = hg.util.setFile("/tmp/setFile/txt2", "txt2 - bla");335 strictEqual(status, true, "Overwriting text file OK.");336 strictEqual(fs.tmp.setFile.txt2, "txt2 - bla", "Checked overwriting.");337 // remove under338 hg.state.makeDir("setFileUnder");339 hg.state.changeDir("setFileUnder");340 var x = hg.util.setFile("../", {});341 deepEqual(fs.tmp.setFile, {}, "Under removed");342 strictEqual(hg.state.computer.pwd, "/", "PWD = root");343 344 hg.state.changeDir(pwd);345});346test("randomChoice", function () {347 var list = [1,2,3,4,5,6,7,8,9],348 util = HackerGame.util,349 contains = function(array, elt, message) {350 ok(_.contains(array, elt), message);351 };352 for (var i = 0; i < 100; i++) {353 contains(list, util.randomChoice(list), "List contains random element");354 }...

Full Screen

Full Screen

browser_privatebrowsing_DownloadLastDirWithCPS.js

Source:browser_privatebrowsing_DownloadLastDirWithCPS.js Github

copy

Full Screen

...30 downloadLastDir.getFileAsync(aURI, function(result) {31 moveAlong(result);32 });33}34function setFile(downloadLastDir, aURI, aValue) {35 downloadLastDir.setFile(aURI, aValue);36 executeSoon(moveAlong);37}38function clearHistoryAndWait() {39 clearHistory();40 executeSoon(() => executeSoon(moveAlong));41}42/*43 * ===================44 * Function with tests45 * ===================46 */47function runTest() {48 let FileUtils =49 Cu.import("resource://gre/modules/FileUtils.jsm", {}).FileUtils;50 let DownloadLastDir =51 Cu.import("resource://gre/modules/DownloadLastDir.jsm", {}).DownloadLastDir;52 let tmpDir = FileUtils.getDir("TmpD", [], true);53 let dir1 = newDirectory();54 let dir2 = newDirectory();55 let dir3 = newDirectory();56 let uri1 = Services.io.newURI("http://test1.com/", null, null);57 let uri2 = Services.io.newURI("http://test2.com/", null, null);58 let uri3 = Services.io.newURI("http://test3.com/", null, null);59 let uri4 = Services.io.newURI("http://test4.com/", null, null);60 // cleanup functions registration61 registerCleanupFunction(function () {62 Services.prefs.clearUserPref("browser.download.lastDir.savePerSite");63 Services.prefs.clearUserPref("browser.download.lastDir");64 [dir1, dir2, dir3].forEach(dir => dir.remove(true));65 win.close();66 pbWin.close();67 });68 function checkDownloadLastDir(gDownloadLastDir, aLastDir) {69 is(gDownloadLastDir.file.path, aLastDir.path,70 "gDownloadLastDir should point to the expected last directory");71 getFile(gDownloadLastDir, uri1);72 }73 function checkDownloadLastDirNull(gDownloadLastDir) {74 is(gDownloadLastDir.file, null, "gDownloadLastDir should be null");75 getFile(gDownloadLastDir, uri1);76 }77 /*78 * ================================79 * Create a regular and a PB window80 * ================================81 */82 let win = yield createWindow({private: false});83 let pbWin = yield createWindow({private: true});84 let downloadLastDir = new DownloadLastDir(win);85 let pbDownloadLastDir = new DownloadLastDir(pbWin);86 /*87 * ==================88 * Beginning of tests89 * ==================90 */91 is(typeof downloadLastDir, "object",92 "downloadLastDir should be a valid object");93 is(downloadLastDir.file, null,94 "LastDir pref should be null to start with");95 // set up last dir96 yield setFile(downloadLastDir, null, tmpDir);97 is(downloadLastDir.file.path, tmpDir.path,98 "LastDir should point to the tmpDir");99 isnot(downloadLastDir.file, tmpDir,100 "downloadLastDir.file should not be pointing to tmpDir");101 // set uri1 to dir1, all should now return dir1102 // also check that a new object is returned103 yield setFile(downloadLastDir, uri1, dir1);104 is(downloadLastDir.file.path, dir1.path,105 "downloadLastDir should return dir1");106 isnot(downloadLastDir.file, dir1,107 "downloadLastDir.file should not return dir1");108 is((yield getFile(downloadLastDir, uri1)).path, dir1.path,109 "uri1 should return dir1"); // set in CPS110 isnot((yield getFile(downloadLastDir, uri1)), dir1,111 "getFile on uri1 should not return dir1");112 is((yield getFile(downloadLastDir, uri2)).path, dir1.path,113 "uri2 should return dir1"); // fallback114 isnot((yield getFile(downloadLastDir, uri2)), dir1,115 "getFile on uri2 should not return dir1");116 is((yield getFile(downloadLastDir, uri3)).path, dir1.path,117 "uri3 should return dir1"); // fallback118 isnot((yield getFile(downloadLastDir, uri3)), dir1,119 "getFile on uri3 should not return dir1");120 is((yield getFile(downloadLastDir, uri4)).path, dir1.path,121 "uri4 should return dir1"); // fallback122 isnot((yield getFile(downloadLastDir, uri4)), dir1,123 "getFile on uri4 should not return dir1");124 // set uri2 to dir2, all except uri1 should now return dir2125 yield setFile(downloadLastDir, uri2, dir2);126 is(downloadLastDir.file.path, dir2.path,127 "downloadLastDir should point to dir2");128 is((yield getFile(downloadLastDir, uri1)).path, dir1.path,129 "uri1 should return dir1"); // set in CPS130 is((yield getFile(downloadLastDir, uri2)).path, dir2.path,131 "uri2 should return dir2"); // set in CPS132 is((yield getFile(downloadLastDir, uri3)).path, dir2.path,133 "uri3 should return dir2"); // fallback134 is((yield getFile(downloadLastDir, uri4)).path, dir2.path,135 "uri4 should return dir2"); // fallback136 // set uri3 to dir3, all except uri1 and uri2 should now return dir3137 yield setFile(downloadLastDir, uri3, dir3);138 is(downloadLastDir.file.path, dir3.path,139 "downloadLastDir should point to dir3");140 is((yield getFile(downloadLastDir, uri1)).path, dir1.path,141 "uri1 should return dir1"); // set in CPS142 is((yield getFile(downloadLastDir, uri2)).path, dir2.path,143 "uri2 should return dir2"); // set in CPS144 is((yield getFile(downloadLastDir, uri3)).path, dir3.path,145 "uri3 should return dir3"); // set in CPS146 is((yield getFile(downloadLastDir, uri4)).path, dir3.path,147 "uri4 should return dir4"); // fallback148 // set uri1 to dir2, all except uri3 should now return dir2149 yield setFile(downloadLastDir, uri1, dir2);150 is(downloadLastDir.file.path, dir2.path,151 "downloadLastDir should point to dir2");152 is((yield getFile(downloadLastDir, uri1)).path, dir2.path,153 "uri1 should return dir2"); // set in CPS154 is((yield getFile(downloadLastDir, uri2)).path, dir2.path,155 "uri2 should return dir2"); // set in CPS156 is((yield getFile(downloadLastDir, uri3)).path, dir3.path,157 "uri3 should return dir3"); // set in CPS158 is((yield getFile(downloadLastDir, uri4)).path, dir2.path,159 "uri4 should return dir2"); // fallback160 yield clearHistoryAndWait();161 // check clearHistory removes all data162 is(downloadLastDir.file, null, "clearHistory removes all data");163 //is(Services.contentPrefs.hasPref(uri1, "browser.download.lastDir", null),164 // false, "LastDir preference should be absent");165 is((yield getFile(downloadLastDir, uri1)), null, "uri1 should point to null");166 is((yield getFile(downloadLastDir, uri2)), null, "uri2 should point to null");167 is((yield getFile(downloadLastDir, uri3)), null, "uri3 should point to null");168 is((yield getFile(downloadLastDir, uri4)), null, "uri4 should point to null");169 yield setFile(downloadLastDir, null, tmpDir);170 // check data set outside PB mode is remembered171 is((yield checkDownloadLastDir(pbDownloadLastDir, tmpDir)).path, tmpDir.path, "uri1 should return the expected last directory");172 is((yield checkDownloadLastDir(downloadLastDir, tmpDir)).path, tmpDir.path, "uri1 should return the expected last directory");173 yield clearHistoryAndWait();174 yield setFile(downloadLastDir, uri1, dir1);175 // check data set using CPS outside PB mode is remembered176 is((yield checkDownloadLastDir(pbDownloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory");177 is((yield checkDownloadLastDir(downloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory");178 yield clearHistoryAndWait();179 // check data set inside PB mode is forgotten180 yield setFile(pbDownloadLastDir, null, tmpDir);181 is((yield checkDownloadLastDir(pbDownloadLastDir, tmpDir)).path, tmpDir.path, "uri1 should return the expected last directory");182 is((yield checkDownloadLastDirNull(downloadLastDir)), null, "uri1 should return the expected last directory");183 yield clearHistoryAndWait();184 // check data set using CPS inside PB mode is forgotten185 yield setFile(pbDownloadLastDir, uri1, dir1);186 is((yield checkDownloadLastDir(pbDownloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory");187 is((yield checkDownloadLastDirNull(downloadLastDir)), null, "uri1 should return the expected last directory");188 // check data set outside PB mode but changed inside is remembered correctly189 yield setFile(downloadLastDir, uri1, dir1);190 yield setFile(pbDownloadLastDir, uri1, dir2);191 is((yield checkDownloadLastDir(pbDownloadLastDir, dir2)).path, dir2.path, "uri1 should return the expected last directory");192 is((yield checkDownloadLastDir(downloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory");193 /*194 * ====================195 * Create new PB window196 * ====================197 */198 // check that the last dir store got cleared in a new PB window199 pbWin.close();200 // And give it time to close201 executeSoon(moveAlong);202 yield;203 pbWin = yield createWindow({private: true});204 pbDownloadLastDir = new DownloadLastDir(pbWin);205 is((yield checkDownloadLastDir(pbDownloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory");206 yield clearHistoryAndWait();207 // check clearHistory inside PB mode clears data outside PB mode208 yield setFile(pbDownloadLastDir, uri1, dir2);209 yield clearHistoryAndWait();210 is((yield checkDownloadLastDirNull(downloadLastDir)), null, "uri1 should return the expected last directory");211 is((yield checkDownloadLastDirNull(pbDownloadLastDir)), null, "uri1 should return the expected last directory");212 // check that disabling CPS works213 Services.prefs.setBoolPref("browser.download.lastDir.savePerSite", false);214 yield setFile(downloadLastDir, uri1, dir1);215 is(downloadLastDir.file.path, dir1.path, "LastDir should be set to dir1");216 is((yield getFile(downloadLastDir, uri1)).path, dir1.path, "uri1 should return dir1");217 is((yield getFile(downloadLastDir, uri2)).path, dir1.path, "uri2 should return dir1");218 is((yield getFile(downloadLastDir, uri3)).path, dir1.path, "uri3 should return dir1");219 is((yield getFile(downloadLastDir, uri4)).path, dir1.path, "uri4 should return dir1");220 downloadLastDir.setFile(uri2, dir2);221 is(downloadLastDir.file.path, dir2.path, "LastDir should be set to dir2");222 is((yield getFile(downloadLastDir, uri1)).path, dir2.path, "uri1 should return dir2");223 is((yield getFile(downloadLastDir, uri2)).path, dir2.path, "uri2 should return dir2");224 is((yield getFile(downloadLastDir, uri3)).path, dir2.path, "uri3 should return dir2");225 is((yield getFile(downloadLastDir, uri4)).path, dir2.path, "uri4 should return dir2");226 Services.prefs.clearUserPref("browser.download.lastDir.savePerSite");227 // check that passing null to setFile clears the stored value228 yield setFile(downloadLastDir, uri3, dir3);229 is((yield getFile(downloadLastDir, uri3)).path, dir3.path, "LastDir should be set to dir3");230 yield setFile(downloadLastDir, uri3, null);231 is((yield getFile(downloadLastDir, uri3)), null, "uri3 should return null");232 yield clearHistoryAndWait();...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

1// 写真の保存2let config = {3 apiKey: "AIzaSyDHCI9HelAf6SLGaO8BCrm4f20TvFeyhlU",4 authDomain: "labs-2e127.firebaseapp.com",5 databaseURL: "https://labs-2e127.firebaseio.com",6 projectId: "labs-2e127",7 storageBucket: "labs-2e127.appspot.com",8 messagingSenderId: "746225726271",9 appId: "1:746225726271:web:5590c90b37a9c2b87b198a"10};11firebase.initializeApp(config);12const form = document.querySelector('form');13const setfile = document.getElementById("setFile");14const storage = firebase.storage();15const imgSample = document.getElementById("imgSample");16let file_name;17let blob;18// setfile変更19setfile.addEventListener("change", e => {20 let file = e.target.files;21 file_name = file[0].name;22 blob = new Blob(file, { type: "image/jpeg" });23 console.warn(blob);24});25// submit26form.addEventListener('submit', e => {27 e.preventDefault();28 let uploadRef = storage.ref('images/').child(file_name);29 uploadRef.put(blob).then(snapshot => {30 console.log(snapshot.state);31 uploadRef.getDownloadURL().then(url => {32 imgSample.style.backgroundImage = "url("+url+")";33 }).catch(error => {34 console.log(error);35 });36 });37 file_name = '';38 blob = '';39});40// 41const date = new Date();42const year = date.getFullYear();43const month = date.getMonth()+1;44const day = date.getDate();45const time = `${year}/${month}/${day}`;46$("#send").on("click",function(){47database.push({48 name:$("#name").val(),49 store:$("#store").val(),50 genre:$("#genre").val(),51 price:$("#price").val(),52 lat:$("#lat").val(),53 lng:$("#lng").val(),54 lng:$("#lng").val(),55 setfile:$("#setfile").val(),56 time:time,57 });58 $("#name").val("");59 $("#store").val("");60 $("#genre").val("");61 $("#price").val("");62 $("#lat").val("");63 $("#lng").val("");64 $("#setfile").val("");65 $("#dialog").fadeOut();66});67// 68$("#post").on("click",function(){69 $("#dialog").dialog();70});71let infowindow = new google.maps.InfoWindow();72function initialize() {73database.on("child_added",function(data){74const v = data.val(); //データ取得75const n = data.name; 76const s = data.store; 77const g = data.genre; 78const pr = data.price; 79const lat = data.lat; 80const lng = data.lng; 81const setfile = data.setfile;82console.log(v.lat,v.lng);83var point = new google.maps.LatLng(v.lat,v.lng);84var marker = create_maker(point, "info",'<p>'+v.store+'('+v.genre+') by'+v.name+'<br>'+v.price+'<pre>'+v.time+'に投稿</pre></p><img src="'+v.setfile+'">');85});86// ________【1】_________87var option1 = {88zoom: 16,89center: new google.maps.LatLng(35.665140, 139.712516),90mapTypeId: google.maps.MapTypeId.ROADMAP,91};92// 吹き出しを閉じる処理93map1 = new google.maps.Map(document.getElementById("map1"), option1);94google.maps.event.addListener(map1, "click", function() {infowindow.close();});95var point = new google.maps.LatLng(35.666018, 139.716969);96var marker = create_maker(point, "info", "<p>ラス(フランス料理)<br>8,000-10,000円/人</p><img src='https://lh5.googleusercontent.com/p/AF1QipPEnM5dl0u7npt99HN6972COUMi0cQengwm3CCe=w408-h306-k-no' id='photo'/>");97function create_maker(latlng, label, html) {98// マーカーを生成99 var marker1 = new google.maps.Marker({position: latlng, map: map1, title: label});100 // マーカーをマウスオーバーした時の処理101 google.maps.event.addListener(marker1, "mouseover", function() {102 infowindow.setContent(html);103 infowindow.open(map1, marker1);104 });105var marker2 = new google.maps.Marker({position: latlng, map: map2, title: label});106 google.maps.event.addListener(marker2, "mouseover", function() {107 infowindow.setContent(html);108 infowindow.open(map2, marker2);109}); 110google.maps.event.addDomListener(window, "load", initialize);111$('#setfile').on('change', function(){ //ファイルが選択されるたびに動作するイベントハンドラ112 var strFileInfo = $("#setfile")[0].files[0]; //jQueryでファイルオブジェクトを変数にセット113 if(strFileInfo && strFileInfo.type.match('image.*')){ //選択されたファイルが画像であれば、処理を継続114 $('#preview').remove(); //表示中のプレビュー画像があれば、削除しておく115 $('#preview_area').append('<img id="preview" width="260" />'); //横幅300pxの空の画像をプレビューエリアにセット116 fileReader = new FileReader(); //HTML5 のAPI である FileReader() メソッドを初期化117 fileReader.onload = function(event){118 $('#preview').attr('src', event.target.result);119 }120 fileReader.readAsDataURL(strFileInfo); //ローカルフォルダから画像ファイルが読み込まれる121 }...

Full Screen

Full Screen

attach.spec.js

Source:attach.spec.js Github

copy

Full Screen

...18 });19 describe('value', function() {20 it('getVal should return actual input\'s value', function() {21 attach.getVal().should.be.equal('');22 setFile('file.png');23 attach.getVal().should.be.equal('file.png');24 });25 it('should emit "change" event after input value changed', function() {26 var spy = sinon.spy();27 attach.on('change', spy);28 setFile('file.png');29 spy.should.have.been.calledOnce;30 });31 it('should properly extract file name', function() {32 setFile('\\usr\\local\\file.png');33 attach.elem('text').text().should.be.equal('file.png');34 });35 it('should properly extract file extension', function() {36 setFile('file.png');37 attach.findBlockInside('icon').getMod('file').should.be.equal('png');38 setFile('file.zip');39 attach.findBlockInside('icon').getMod('file').should.be.equal('archive');40 setFile('file.docx');41 attach.findBlockInside('icon').getMod('file').should.be.equal('doc');42 });43 });44 describe('clear', function() {45 it('should reset input\'s value', function() {46 setFile('file.png');47 attach.clear();48 attach.getVal().should.be.equal('');49 });50 it('should emit "change" event after clear', function() {51 var spy = sinon.spy();52 setFile('file.png');53 attach.on('change', spy);54 attach.clear();55 spy.should.have.been.calledOnce;56 attach.clear();57 spy.should.have.been.calledOnce;58 });59 it('should be called after "pointerclick" on "clear" elem', function() {60 var spy = sinon.spy();61 attach.clear = spy;62 setFile('file.png');63 attach.elem('clear').trigger('pointerclick');64 spy.should.have.been.calledOnce;65 });66 });67 describe('enable/disable', function() {68 it('should enable/disable button according to self "disabled" state', function() {69 attach.setMod('disabled');70 attach.findBlockInside('button').hasMod('disabled').should.be.true;71 attach.delMod('disabled');72 attach.findBlockInside('button').hasMod('disabled').should.be.false;73 });74 });75 function setFile(filePath) {76 attach.elem('control')77 .val(filePath)78 .trigger('change');79 }80});81provide();...

Full Screen

Full Screen

UploadForm.js

Source:UploadForm.js Github

copy

Full Screen

...6 const types = ['image/png', 'image/jpeg'];7 const changeHandler = e => {8 let selected = e.target.files[0];9 if (selected && types.includes(selected.type)) {10 setFile(selected);11 setError('');12 } else {13 setFile(null);14 setError('Please select an image file (png or jpeg)');15 }16 }17 return (18 <form>19 <label>20 <input type="file" onChange={changeHandler} />21 <span>+</span>22 </label>23 <div className="output">24 { error && <div className="error">{ error }</div> }25 { file && <div>{ file.name }</div> }26 { file && <ProgressBar file={file} setFile={setFile} /> }27 </div>...

Full Screen

Full Screen

Upload.jsx

Source:Upload.jsx Github

copy

Full Screen

...5const [error, Seterror] = useState(null);6 const changeHandler =(event) =>{7 let selected = event.target.files[0];8 if(selected){9 setFile(selected);10 Seterror('');11 }else{12 setFile(null);13 Seterror('please select the image ');14 }15 };16 return (17 <>18 <form>19 <label>20 <input type="file" onChange={changeHandler} multiple/>21 <span>+</span>22 </label>23 <div className ="output">24 {file && <div>{file.name} </div>}25 { file && <Progress file={file} setFile={setFile} /> }26 </div>...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require("qawolf");2const { setFile } = require("qawolf");3const { chromium } = require("playwright");4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await setFile(page, "input[name=q]", "text.txt");9 await page.click("input[type=submit]");10 await qawolf.stopVideos();11 await browser.close();12})();13const qawolf = require("qawolf");14const { setFiles } = require("qawolf");15const { chromium } = require("playwright");16(async () => {17 const browser = await chromium.launch();18 const context = await browser.newContext();19 const page = await context.newPage();20 await setFiles(page, "input[type=file]", ["text.txt", "text1.txt"]);21 await page.click("input[type=submit]");22 await qawolf.stopVideos();23 await browser.close();24})();25const qawolf = require("qawolf");26const { setSelect } = require("qawolf");27const { chromium } = require("playwright");28(async () => {29 const browser = await chromium.launch();30 const context = await browser.newContext();31 const page = await context.newPage();32 await page.goto("

Full Screen

Using AI Code Generation

copy

Full Screen

1const { setFile } = require("qawolf");2setFile("./test.json");3const { create } = require("qawolf");4const browser = await create({ name: "test" });5const { launch } = require("qawolf");6const browser = await launch();7const { register } = require("qawolf");8await register();9const { create } = require("qawolf");10const browser = await create({ name: "test" });11const { launch } = require("qawolf");12const browser = await launch();13const { register } = require("qawolf");14await register();15const { create } = require("qawolf");16const browser = await create({ name: "test" });17const { launch } = require("qawolf");18const browser = await launch();19const { register } = require("qawolf");20await register();21const { create } = require("qawolf");22const browser = await create({ name: "test" });23const { launch } = require("qawolf");24const browser = await launch();25const { register } = require("qawolf");26await register();27const { create } = require("qawolf");28const browser = await create({ name: "test" });29const { launch } = require("qawolf");30const browser = await launch();31const { register } = require("qawolf");32await register();33const { create } = require("qawolf");34const browser = await create({ name: "test" });

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require('qawolf');2const browser = await qawolf.launch();3const context = await browser.newContext();4const page = await context.newPage();5await page.click('input[type="file"]');6const file = await qawolf.createFile();7await file.setFile('C:\\Users\\test\\Documents\\test.txt');8await page.click('text="Open"');9await page.click('text="Upload"');10await page.click('text="Google Search"');11await qawolf.stopVideos();12await browser.close();13}

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require("qawolf");2const browser = await qawolf.launch();3const page = await browser.newPage();4await qawolf.setFile(page, "input[type='file']", "test.pdf");5await browser.close();6await qawolf.stop();7const qawolf = require("qawolf");8const browser = await qawolf.launch();9const page = await browser.newPage();10await qawolf.setFiles(page, "input[type='file']", [11]);12await browser.close();13await qawolf.stop();14const qawolf = require("qawolf");15const browser = await qawolf.launch();16const page = await browser.newPage();17await qawolf.type(page, "input[type='text']", "Hello World");18await browser.close();19await qawolf.stop();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { setFile } = require('qawolf');2setFile('input[type="file"]', 'file.txt');3const puppeteer = require('puppeteer');4const browser = await puppeteer.launch();5const page = await browser.newPage();6await page.setFile('input[type="file"]', 'file.txt');7const playwright = require('playwright');8const browser = await playwright.chromium.launch();9const page = await browser.newPage();10await page.setFile('input[type="file"]', 'file.txt');11const webdriverio = require('webdriverio');12const browser = await webdriverio.remote({13 capabilities: {14 },15});16await browser.setFile('input[type="file"]', 'file.txt');17import { Selector } from 'testcafe';18fixture('File Upload')19test('Upload a file', async t => {20 await t.setFilesToUpload(Selector('#file-upload'), 'file.txt');21});22cy.get('input[type="file"]').attachFile(fileName);

Full Screen

Using AI Code Generation

copy

Full Screen

1await qawolf.setFile('input[type="file"]', '/home/username/Downloads/test.txt');2await qawolf.setFile('input[type="file"]', '/home/username/Downloads/test.txt', { timeout: 10000 });3await page.waitForSelector('input[type="file"]');4const input = await page.$('input[type="file"]');5await input.uploadFile('/home/username/Downloads/test.txt');6await page.waitForSelector('input[type="file"]');7const input = await page.$('input[type="file"]');8await input.uploadFile('/home/username/Downloads/test.txt', { timeout: 10000 });9await page.setInputFiles('input[type="file"]', '/home/username/Downloads/test.txt');10await page.setInputFiles('input[type="file"]', '/home/username/Downloads/test.txt', { timeout: 10000 });11await browser.chooseFile('input[type="file"]', '/home/username/Downloads/test.txt');12await browser.chooseFile('input[type="file"]', '/home/username/Downloads/test.txt', { timeout: 10000 });13await cy.get('input[type="file"]').attachFile('/home/username/Downloads/test.txt');14await cy.get('input[type="file"]').attachFile('/home/username/Downloads/test.txt', { timeout: 10000 });15await t.setFilesToUpload('input[type="file"]', '/home/username/Downloads/test.txt');16await t.setFilesToUpload('input[type="file"]', '/home/username/Downloads/test.txt', { timeout: 10000 });17const input = await browser.findElement(By.css('input[type="file"]'));18input.sendKeys('/home/username/Downloads/test.txt');19const input = await browser.findElement(By.css('input[type="file"]'));20input.sendKeys('/home/username/Downloads/test.txt', { timeout: 10000 });21await element(by.css('input[type="file"]')).sendKeys('/home/username/Downloads/test.txt');22await element(by.css('input[type="file"]')).sendKeys('/home/username/Downloads/test.txt', { timeout

Full Screen

Using AI Code Generation

copy

Full Screen

1const { setFile } = require("qawolf");2setFile("input[type='file']", "test.txt");3setFile("input[type='file']", "test.txt");4setFile("input[type='file']", "test.txt");5setFile("input[type='file']", "test.txt");6setFile("input[type='file']", "test.txt");7setFile("input[type='file']", "test.txt");8setFile("input[type='file']", "test.txt");9setFile("input[type='file']", "test.txt");

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run qawolf automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful