Best JavaScript code snippet using cypress
wrapper.js
Source:wrapper.js
1const SerialPort = require('serialport');2const EventEmitter = require('events');3const SensorState = require('./core/sensor-state.js');4const SensorCommand = require('./core/sensor-command.js');5const addChecksumToCommandArray = require('./core/packet-utils.js').addChecksumToCommandArray;6const verifyPacket = require('./core/packet-utils.js').verifyPacket;7const PacketHandlers = require('./core/packet-handlers.js');8const ALLOWED_RETRIES = 10; // Number of retries allowed for single command request.9const COMMAND_RETRY_INTERVAL = 150; // Time between sequential retries.10class SDS011Wrapper extends EventEmitter {11 /**12 * Open sensor.13 *14 * @param {string} portPath - Serial port path15 */16 constructor(portPath) {17 super();18 this._port = new SerialPort(portPath, { baudRate: 9600 });19 this._state = new SensorState();20 this._commandQueue = [];21 this._isCurrentlyProcessing = false;22 this._retryCount = 0;23 this._port.on('error', function (err) {24 console.log('Error: ', err.message);25 });26 this._port.on('close', () => {27 console.log('SDS011Wrapper port closed');28 this.close();29 });30 /**31 * Listen for incoming data and react: change internal state so queued commands know that they were completed or emit data.32 */33 this._port.on('data', (data) => {34 if (verifyPacket(data)) {35 var type = data.readUIntBE(1, 1); // Byte offset 1 is command type36 switch (type) {37 case 0xc0:38 PacketHandlers.handle0xC0(data, this._state);39 if (this._state.mode == 'active')40 this.emit('measure', {41 'PM2.5': this._state.pm2p5,42 PM10: this._state.pm1043 });44 break;45 case 0xc5:46 PacketHandlers.handle0xC5(data, this._state);47 break;48 default:49 throw new Error('Unknown packet type: ' + type);50 }51 }52 });53 // Queue first command to "warm-up" the connection and command queue54 this.query().catch((ex) => {55 console.error('SDS011Wrapper error: ' + ex);56 });57 }58 /**59 * Close open connection and cleanup.60 */61 close() {62 if (this._state.closed) {63 console.log('Sensor connection is already closed.');64 return;65 }66 this._port.close();67 this._state.closed = true;68 this._commandQueue.length = 0;69 this.emit('close', {});70 this.removeAllListeners();71 }72 /**73 * Query sensor for it's latest reading.74 *75 * @returns {Promise<object>} Resolved with PM2.5 and PM10 readings. May be rejected if sensor fails to respond after a number of internal retries.76 */77 query() {78 return this._enqueueQueryCommand(this._port, this._state);79 }80 _enqueueQueryCommand(port, state) {81 function prepare() {82 this.state.pm2p5 = undefined;83 this.state.pm10 = undefined;84 }85 const prepareContext = {86 state: state87 };88 function execute() {89 var command = [0xaa, 0xb4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0xab];90 addChecksumToCommandArray(command);91 this.port.write(Buffer.from(command));92 }93 const executeContext = {94 port: port95 };96 function isFullfilled() {97 return this.state.pm2p5 !== undefined && this.state.pm10 !== undefined;98 }99 const isFullfilledContext = {100 state: state101 };102 return new Promise((resolve, reject, onCancel) => {103 function resolveWithReadings() {104 resolve({105 'PM2.5': this.state.pm2p5,106 PM10: this.state.pm10107 });108 }109 const resolveContext = {110 state: state111 };112 const command = new SensorCommand(port, resolveWithReadings.bind(resolveContext), reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext));113 this._enqueueCommand(command);114 });115 }116 /**117 * Set reporting mode. This setting is still effective after power off.118 *119 * @param {('active'|'query')} mode - active: data will be emitted as "data" event, query: new data has to requested manually @see query120 *121 * @returns {Promise} Resolved when mode was set successfully. May be rejected if sensor fails to respond after a number of internal retries.122 */123 setReportingMode(mode) {124 return this._enqueueSetModeCommand(this._port, this._state, mode);125 }126 _enqueueSetModeCommand(port, state, mode) {127 if (mode !== 'active' && mode !== 'query') throw new Error('Invalid mode');128 function prepare() {129 this.state.mode = undefined;130 }131 const prepareContext = {132 state: state133 };134 function execute() {135 var command = [0xaa, 0xb4, 2, 1, this.mode === 'active' ? 0 : 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0xab];136 addChecksumToCommandArray(command);137 this.port.write(Buffer.from(command));138 }139 const executeContext = {140 port: port,141 mode: mode142 };143 function isFullfilled() {144 return this.state.mode === this.setMode;145 }146 const isFullfilledContext = {147 state: this._state,148 setMode: mode149 };150 return new Promise((resolve, reject, onCancel) => {151 const command = new SensorCommand(port, resolve, reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext));152 this._enqueueCommand(command);153 });154 }155 /**156 * Get reporting mode.157 *158 * @returns {Promise} Resolved with either 'active' or 'query'. May be rejected if sensor fails to respond after a number of internal retries.159 */160 getReportingMode() {161 return this._enqueueGetModeCommand(this._port, this._state);162 }163 _enqueueGetModeCommand(port, state) {164 function prepare() {165 this.state.mode = undefined;166 }167 const prepareContext = {168 state: state169 };170 function execute() {171 var command = [0xaa, 0xb4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0xab];172 addChecksumToCommandArray(command);173 this.port.write(Buffer.from(command));174 }175 const executeContext = {176 port: port177 };178 function isFullfilled() {179 return this.state.mode != undefined;180 }181 const isFullfilledContext = {182 state: this._state183 };184 return new Promise((resolve, reject, onCancel) => {185 function resolveWithMode() {186 resolve(this.state.mode);187 }188 const resolveContext = {189 state: state190 };191 const command = new SensorCommand(port, resolveWithMode.bind(resolveContext), reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext));192 this._enqueueCommand(command);193 });194 }195 /**196 * Switch to sleep mode and back. Fan and laser will be turned off while in sleep mode. Any command will wake the device.197 *198 * @param {boolean} shouldSleep - whether device should sleep or not199 *200 * @returns {Promise} Resolved when operation completed successfully. May be rejected if sensor fails to respond after a number of internal retries.201 */202 setSleepSetting(shouldSleep) {203 return this._enqueueSetSleepCommand(this._port, this._state, shouldSleep);204 }205 _enqueueSetSleepCommand(port, state, shouldSleep) {206 function prepare() {207 this.state.isSleeping = undefined;208 }209 const prepareContext = {210 state: state211 };212 function execute() {213 var command = [0xaa, 0xb4, 6, 1, shouldSleep ? 0 : 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0xab];214 addChecksumToCommandArray(command);215 this.port.write(Buffer.from(command));216 }217 const executeContext = {218 port: port,219 shouldSleep: shouldSleep220 };221 function isFullfilled() {222 return this.state.isSleeping === this.shouldSleep;223 }224 const isFullfilledContext = {225 state: this._state,226 shouldSleep: shouldSleep227 };228 return new Promise((resolve, reject, onCancel) => {229 const command = new SensorCommand(port, resolve, reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext));230 this._enqueueCommand(command);231 });232 }233 /**234 * Read software version. It will be presented in "year-month-day" format.235 *236 * @returns {Promise<string>} - Resolved with sensor firmware version. May be rejected if sensor fails to respond after a number of internal retries.237 */238 getVersion() {239 return this._enqueueGetVersionCommand(this._port, this._state);240 }241 _enqueueGetVersionCommand(port, state) {242 function prepare() {243 this.state.firmware = undefined;244 }245 const prepareContext = {246 state: state247 };248 function execute() {249 var command = [0xaa, 0xb4, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0xab];250 addChecksumToCommandArray(command);251 this.port.write(Buffer.from(command));252 }253 const executeContext = {254 port: port255 };256 function isFullfilled() {257 return this.state.firmware !== undefined;258 }259 const isFullfilledContext = {260 state: this._state261 };262 return new Promise((resolve, reject, onCancel) => {263 function resolveWithFirmwareVersion() {264 resolve(this.state.firmware);265 }266 const resolveContext = {267 state: state268 };269 const command = new SensorCommand(270 port,271 resolveWithFirmwareVersion.bind(resolveContext),272 reject,273 prepare.bind(prepareContext),274 execute.bind(executeContext),275 isFullfilled.bind(isFullfilledContext)276 );277 this._enqueueCommand(command);278 });279 }280 /**281 * Set working period of the sensor. This setting is still effective after power off.282 *283 * @param {number} time - Working time (0 - 30 minutes). Sensor will work continuously when set to 0.284 *285 * @returns {Promise} Resolved when period was changed successfully. May be rejected if sensor fails to respond after a number of internal retries.286 */287 setWorkingPeriod(time) {288 if (time < 0 || time > 30) throw new Error('Invalid argument.');289 return this._enqueueSetWorkingPeriodCommand(this._port, this._state, time);290 }291 _enqueueSetWorkingPeriodCommand(port, state, time) {292 function prepare() {293 this.state.workingPeriod = undefined;294 }295 var prepareContext = {296 state: state297 };298 function execute() {299 var command = [0xaa, 0xb4, 8, 1, this.time, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0xab];300 addChecksumToCommandArray(command);301 this.port.write(Buffer.from(command)); // Send the command to the sensor302 }303 var executeContext = {304 port: port,305 time: time306 };307 function isFullfilled() {308 return this.state.workingPeriod === this.setPeriod;309 }310 var isFullfilledContext = {311 state: this._state,312 setPeriod: time313 };314 return new Promise((resolve, reject, onCancel) => {315 const command = new SensorCommand(port, resolve, reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext));316 this._enqueueCommand(command);317 });318 }319 /**320 * Get current working period.321 *322 * @returns {Promise<Number>} Resolved with current period setting. May be rejected if sensor fails to respond after a number of internal retries.323 */324 getWorkingPeriod() {325 return this._enqueueGetWorkingPeriodCommand(this._port, this._state);326 }327 _enqueueGetWorkingPeriodCommand(port, state) {328 function prepare() {329 this.state.workingPeriod = undefined;330 }331 var prepareContext = {332 state: state333 };334 function execute() {335 var command = [0xaa, 0xb4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0xab];336 addChecksumToCommandArray(command);337 this.port.write(Buffer.from(command)); // Send the command to the sensor338 }339 var executeContext = {340 port: port341 };342 function isFullfilled() {343 return this.state.workingPeriod !== undefined;344 }345 var isFullfilledContext = {346 state: this._state347 };348 return new Promise((resolve, reject, onCancel) => {349 function resolveWithTime() {350 resolve(this.state.workingPeriod);351 }352 const resolveContext = {353 state: state354 };355 const command = new SensorCommand(port, resolveWithTime.bind(resolveContext), reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext));356 this._enqueueCommand(command);357 });358 }359 _enqueueCommand(command) {360 if (command.constructor.name !== 'SensorCommand') throw new Error('Argument of type "SensorCommand" is required.');361 this._commandQueue.push(command);362 if (!this._isCurrentlyProcessing) {363 this._processCommands();364 }365 }366 _processCommands() {367 this._isCurrentlyProcessing = true;368 const cmd = this._commandQueue[0];369 // Run prepare command for the first execution of new command370 if (this._retryCount == 0 && cmd !== undefined) cmd.prepare();371 // Reject command if it failed after defined number of retries372 if (++this._retryCount > ALLOWED_RETRIES) {373 const faultyCommand = this._commandQueue.shift();374 faultyCommand.failureCallback(); // Let the world know375 this._retryCount = 0;376 this._processCommands(); // Move to the next command377 return;378 }379 if (this._commandQueue.length > 0) {380 if (cmd.isFullfilled()) {381 this._commandQueue.shift(); // Fully processed, remove from the queue.382 this._retryCount = 0;383 cmd.successCallback();384 this._processCommands(); // Move to the next command385 } else {386 // Command completion condition was not met. Run command and run check after some time.387 cmd.execute();388 setTimeout(this._processCommands.bind(this), COMMAND_RETRY_INTERVAL);389 }390 } else {391 // Processed all pending commands.392 this._isCurrentlyProcessing = false;393 this._retryCount = 0;394 }395 }396}...
testRenderHerman.js
Source:testRenderHerman.js
...58 afterEach(function () {59 del.sync(`${this.dest}/*`);60 });61 it('renders index template', function (done) {62 prepareContext({63 data: [],64 })65 .then((ctx) => renderHerman(this.dest, ctx))66 .then(() => access(`${this.dest}/index.html`))67 .then(() => {68 assert.ok(true);69 done();70 })71 .catch(done);72 });73 it('copies an internal shortcutIcon', function (done) {74 const shortcutIcon = `${__dirname}/fixtures/img/favicon.ico`;75 const expectedShortcutIcon = `${this.dest}/assets/img/favicon.ico`;76 prepareContext({77 data: [],78 shortcutIcon,79 })80 .then((ctx) => renderHerman(this.dest, ctx))81 .then(() => access(expectedShortcutIcon))82 .then(() => {83 assert.ok(true);84 done();85 })86 .catch(done);87 });88 it('ignores an external shortcutIcon', function (done) {89 const expectedShortcutIcon = `${this.dest}/assets/img/favicon.ico`;90 prepareContext({91 data: [],92 shortcutIcon: 'http://example.com/img/favicon.ico',93 })94 .then((ctx) => renderHerman(this.dest, ctx))95 .then(() => access(expectedShortcutIcon))96 .then(() => {97 // The file should not have been copied98 assert.fail();99 done();100 })101 .catch(() => {102 assert.ok(true);103 done();104 });105 });106 it('handles customCSS', function (done) {107 prepareContext({108 data: [],109 customCSS: {110 path: `${__dirname}/fixtures/css/main.css`,111 },112 })113 .then((ctx) => renderHerman(this.dest, ctx))114 .then(() => access(`${this.dest}/assets/custom/main.css`))115 .then(() => {116 assert.ok(true);117 done();118 })119 .catch(done);120 });121 it('handles customCSSFiles', function (done) {122 prepareContext({123 data: [],124 customCSS: {125 path: `${__dirname}/fixtures/css/main.css`,126 },127 customCSSFiles: [`${__dirname}/fixtures/icons/not-an-svg-icon.png`],128 })129 .then((ctx) => renderHerman(this.dest, ctx))130 .then(() => access(`${this.dest}/assets/custom/not-an-svg-icon.png`))131 .then(() => {132 assert.ok(true);133 done();134 })135 .catch(done);136 });137 it('resolves local fonts', function (done) {138 prepareContext({139 herman: {140 fontPath: 'fixtures/fonts',141 },142 data: [],143 localFonts: [`${__dirname}/fixtures/fonts/sample.ttf`],144 })145 .then((ctx) => {146 ctx.dir = __dirname;147 return renderHerman(this.dest, ctx);148 })149 .then(() => access(`${this.dest}/assets/fonts/sample.ttf`))150 .then(() => {151 assert.ok(true);152 done();153 })154 .catch(done);155 });156 it('renders extraDocs', function (done) {157 prepareContext({158 data: [],159 extraDocs: [160 {161 filename: 'simple',162 name: 'simple',163 text: '<h1 id="a-simple-file">A simple file</h1>\n',164 },165 ],166 })167 .then((ctx) => renderHerman(this.dest, ctx))168 .then(() => access(`${this.dest}/simple.html`))169 .then(() => {170 assert.ok(true);171 done();172 })173 .catch(done);174 });175 it('renders a page for each group', function (done) {176 prepareContext({177 data: [178 {179 description: 'This is some text',180 context: {181 type: 'variable',182 },183 group: ['group1'],184 access: 'public',185 },186 {187 description: 'This is more text',188 context: {189 type: 'variable',190 },191 group: ['group2'],192 access: 'public',193 },194 {195 description: 'This is yet more text',196 context: {197 type: 'variable',198 },199 group: ['fail'],200 access: 'public',201 },202 ],203 groups: {204 'Group 1 Parent': {205 group1: 'Group 1',206 },207 group2: 'Group 2',208 },209 display: {210 access: ['private', 'public'],211 },212 })213 .then((ctx) => {214 // Test group that doesn't exist215 delete ctx.groups.fail;216 return renderHerman(this.dest, ctx);217 })218 .then(() => access(`${this.dest}/group1.html`))219 .then(() => access(`${this.dest}/group2.html`))220 .then(() => {221 assert.ok(true);222 done();223 })224 .catch(done);225 });226 it('generates search data', function (done) {227 prepareContext({228 data: [],229 })230 .then((ctx) => renderHerman(this.dest, ctx))231 .then(() => access(`${this.dest}/search-data.json`))232 .then(() => {233 assert.ok(true);234 done();235 })236 .catch(done);237 });...
prepareContext.js
Source:prepareContext.js
...12 });13 var context = view.renderContext();14 15 // test with firstTime16 view.prepareContext(context, YES);17 equals(context.id(), 'foo', 'did set id');18 ok(context.hasClass('bar'), 'did set class names');19});20test("check that testing without first time still renders to a context", function() {21 var view = SC.View.create({22 layerId: "foo", 23 classNames: ["bar"],24 createRenderer: function(t) { return undefined; }25 });26 var context = view.renderContext();27 view.prepareContext(context, NO);28 ok(context.id() === 'foo', 'set id');29 ok(context.hasClass('bar'), 'set class name');30});31test("invokes renderLayout each time", function() {32 var runCount = 0;33 var context, isFirstTime ;34 var view = SC.View.create({35 renderLayout: function(aContext, firstTime) { 36 equals(aContext, context, 'passed context');37 equals(firstTime, isFirstTime, 'passed firstTime');38 runCount++; 39 }40 });41 42 // test w/ firstTime43 context = view.renderContext();44 isFirstTime = YES ;45 view.prepareContext(context, YES);46 equals(runCount, 1, 'should call renderLayout');47 48 // test w/o firstTime49 runCount = 0 ;50 context = view.renderContext();51 isFirstTime = NO ;52 view.prepareContext(context, NO);53 equals(runCount, 1, 'should call renderLayout');54});55test("adds text-selectable class if view has isTextSelectable", function() {56 var view = SC.View.create() ;57 var context ;58 59 context = view.renderContext();60 view.set('isTextSelectable', YES);61 view.prepareContext(context, YES);62 ok(context.hasClass('allow-select'), 'should have text-selectable class');63 64 context = view.renderContext();65 view.set('isTextSelectable', NO);66 view.prepareContext(context, YES);67 ok(!context.hasClass('allow-select'), 'should NOT have text-selectable class');68 69});70test("adds disabled class if view isEnabled = NO", function() {71 var view = SC.View.create() ;72 var context ;73 74 context = view.renderContext();75 view.set('isEnabled', YES);76 view.prepareContext(context, YES);77 ok(!context.hasClass('disabled'), 'should NOT have disabled class');78 79 context = view.renderContext();80 view.set('isEnabled', NO);81 view.prepareContext(context, YES);82 ok(context.hasClass('disabled'), 'should have disabled class');83 84});85test("adds aria-disabled attribute if view isEnabled = NO", function() {86 var view = SC.View.create(),87 context = view.renderContext();88 89 context = view.renderContext();90 view.set('isEnabled', NO);91 view.prepareContext(context, YES);92 ok(context.attr('aria-disabled'), 'should have the aria-disabled attribute');93 94 view.set('isEnabled', YES);95 view.prepareContext(context, YES);96 ok(context.attr('aria-disabled') === null, 'should NOT have the aria-disabled attribute');97 98});99test("adds sc-hidden class if view isVisible = NO", function() {100 var view = SC.View.create() ;101 var context ;102 103 context = view.renderContext();104 view.set('isVisible', YES);105 view.prepareContext(context, YES);106 ok(!context.hasClass('sc-hidden'), 'should NOT have sc-hidden class');107 108 context = view.renderContext();109 view.set('isVisible', NO);110 view.prepareContext(context, YES);111 ok(context.hasClass('sc-hidden'), 'should have sc-hidden class'); 112});113test("invokes render() passing context & firstTime", function() {114 var runCount = 0;115 var context, isFirstTime ;116 var view = SC.View.create({117 render: function(theContext, firstTime) {118 equals(context, theContext, 'context passed');119 equals(firstTime, isFirstTime, 'firstTime passed');120 runCount++;121 }122 }) ;123 124 context = view.renderContext();125 isFirstTime = YES;126 view.prepareContext(context, YES); 127 equals(runCount, 1, 'did invoke render()');128 runCount = 0 ;129 context = view.renderContext();130 isFirstTime = NO;131 view.prepareContext(context, NO); 132 equals(runCount, 1, 'did invoke render()');133});134test("invokes renderMixin() from mixins, passing context & firstTime", function() {135 var runCount = 0;136 var context, isFirstTime ;137 138 // define a few mixins to make sure this works w/ multiple mixins 139 var mixinA = {140 renderMixin: function(theContext, firstTime) {141 equals(context, theContext, 'context passed');142 equals(firstTime, isFirstTime, 'firstTime passed');143 runCount++;144 }145 };146 var mixinB = {147 renderMixin: function(theContext, firstTime) {148 equals(context, theContext, 'context passed');149 equals(firstTime, isFirstTime, 'firstTime passed');150 runCount++;151 }152 };153 var view = SC.View.create(mixinA, mixinB) ;154 155 context = view.renderContext();156 isFirstTime = YES;157 view.prepareContext(context, YES); 158 equals(runCount, 2, 'did invoke renderMixin() from both mixins');159 runCount = 0 ;160 context = view.renderContext();161 isFirstTime = NO;162 view.prepareContext(context, NO); 163 equals(runCount, 2, 'did invoke renderMixin() from both mixins');164});165test("Properly sets cursor class", function() {166 var view = SC.View.create();167 var context = view.renderContext();168 var cursor = SC.Cursor.create({className: 'testClass'});169 view.set('cursor', cursor);170 view.prepareContext(context, YES);171 ok(context.hasClass(cursor.get('className')), "Should have cursor object's class");172 //TODO: Test for setting string.173 var view2 = SC.View.create();174 view.appendChild(view2);175 var context = view2.renderContext();176 view2.prepareContext(context, YES);177 ok(context.hasClass(cursor.get('className')), "Cursorless child view should inherit parent view's cursor.");...
testPrepareContext.js
Source:testPrepareContext.js
...4const sinon = require('sinon');5const prepareContext = require('../../lib/prepareContext');6describe('prepareContext', () => {7 it('resolves to a context', (done) => {8 prepareContext({9 data: [],10 description: 'foo',11 })12 .then((ctx) => {13 const expected = {14 display: {15 access: ['public', 'private'],16 alias: false,17 watermark: true,18 },19 groups: {20 undefined: 'General',21 },22 orderedGroups: ['undefined'],23 subgroupsByGroup: {},24 sort: ['group', 'file', 'line', 'access'],25 herman: {26 nunjucks: {},27 sass: {},28 },29 description: '<p>foo</p>\n',30 data: [],31 byGroup: {},32 };33 assert.deepStrictEqual(ctx, expected);34 done();35 })36 .catch(done);37 });38 it('sets extraDocs', (done) => {39 const warn = sinon.fake();40 prepareContext({41 data: [],42 herman: {43 extraDocs: [44 `${__dirname}/fixtures/markdown/simple.md`,45 {46 path: `${__dirname}/fixtures/markdown/complex.md`,47 name: 'A complex doc',48 },49 {50 path: `${__dirname}/fixtures/markdown/complex.md`,51 },52 `${__dirname}/no/such/file`,53 ],54 },55 logger: {56 warn,57 },58 })59 .then((ctx) => {60 const simple = {61 filename: 'simple',62 name: 'simple',63 text: '<h1 id="a-simple-file" tabindex="-1">A simple file</h1>\n',64 };65 const complex = {66 filename: 'complex',67 name: 'A complex doc',68 text: '<h1 id="a-complex-file" tabindex="-1">A complex file</h1>\n',69 };70 const complex2 = {71 filename: 'complex',72 name: 'complex',73 text: '<h1 id="a-complex-file" tabindex="-1">A complex file</h1>\n',74 };75 assert.deepStrictEqual(ctx.extraDocs, [simple, complex, complex2]);76 sinon.assert.calledOnce(warn);77 done();78 })79 .catch(done);80 });81 it('sets extraLinks', (done) => {82 prepareContext({83 data: [],84 herman: {85 extraLinks: ['https://www.oddbird.net'],86 },87 })88 .then((ctx) => {89 assert.deepStrictEqual(ctx.extraLinks, ['https://www.oddbird.net']);90 done();91 })92 .catch(done);93 });94 it('loads a Sass JSON file', (done) => {95 prepareContext({96 data: [],97 herman: {98 sass: {99 jsonFile: `${__dirname}/fixtures/css/json.css`,100 },101 },102 })103 .then((ctx) => {104 assert.ok(ctx.sassjson.colors !== undefined);105 done();106 })107 .catch(done);108 });109 it('logs a missing Sass JSON file', (done) => {110 const warn = sinon.fake();111 prepareContext({112 data: [],113 logger: { warn },114 herman: {115 sass: {116 jsonFile: `${__dirname}/fixtures/css/missing-json.css`,117 },118 },119 })120 .then(() => {121 sinon.assert.calledOnce(warn);122 done();123 })124 .catch(done);125 });126 it('removes bogus context', (done) => {127 const item = {128 commentRange: {129 start: 0,130 end: 5,131 },132 context: {133 type: 'unknown',134 line: {135 start: 10,136 end: 15,137 },138 },139 file: {},140 group: ['test'],141 access: 'public',142 };143 const item2 = {144 commentRange: {145 start: 0,146 end: 5,147 },148 context: {149 name: 'Test\nItem',150 line: {151 start: 6,152 end: 7,153 },154 },155 file: {},156 group: ['test'],157 access: 'public',158 };159 const expected = [160 extend({}, item, {161 context: {162 type: 'prose',163 line: {164 start: 0,165 end: 5,166 },167 },168 groupName: {169 test: 'test',170 },171 }),172 extend({}, item2, {173 groupName: {174 test: 'test',175 },176 }),177 ];178 prepareContext({179 data: [item, item2],180 })181 .then((ctx) => {182 assert.deepStrictEqual(ctx.data, expected);183 done();184 })185 .catch(done);186 });187 it('warns if prose block uses custom annotation with key', (done) => {188 const logger = { warn: sinon.fake() };189 const item = {190 commentRange: {191 start: 0,192 end: 5,193 },194 context: {195 name: 'Test\nItem',196 line: {197 start: 8,198 end: 10,199 },200 },201 colors: { key: '' },202 file: {},203 group: ['test'],204 access: 'public',205 };206 const expected = [207 extend({}, item, {208 context: {209 type: 'prose',210 line: {211 start: 0,212 end: 5,213 },214 },215 groupName: {216 test: 'test',217 },218 }),219 ];220 prepareContext({221 logger,222 data: [item],223 })224 .then((ctx) => {225 assert.deepStrictEqual(ctx.data, expected);226 sinon.assert.calledOnce(logger.warn);227 done();228 })229 .catch(done);230 });...
actions.spec.js
Source:actions.spec.js
...7describe('actions', () => {8 describe('startTask', () => {9 it('adds an entry and logs', () => {10 // GIVEN11 const ctx = prepareContext({}, TEST_NOW)12 // WHEN13 startTask(ctx)('eat')14 // THEN15 assertStdOut(ctx, `Task eat started at ${TEST_MOMENT.format("HH:mm")}.\n`)16 assertState(ctx, {17 days: {18 "1981-07-23": [19 "11:12|start|eat"20 ]21 }22 })23 })24 it('adds and entry with override time', ()=>{25 // GIVEN26 const ctx = prepareContext({}, TEST_NOW)27 // WHEN28 startTask(ctx)('eat', '13:37')29 // THEN30 assertStdOut(ctx, `Task eat started at 13:37.\n`)31 assertState(ctx,{32 days: {33 "1981-07-23" : [34 "13:37|start|eat"35 ]36 }37 })38 })39 })40 describe('stopTask', () => {41 it('adds an entry and logs', () => {42 // GIVEN43 const ctx = prepareContext({}, TEST_NOW)44 // WHEN45 stopTask(ctx)()46 // THEN47 assertStdOut(ctx, `Task stopped at ${TEST_MOMENT.format("HH:mm")}.\n`)48 assertState(ctx, {49 days: {50 "1981-07-23": [51 "11:12|stop"52 ]53 }54 })55 })56 it('adds an entry with overrideTime', ()=>{57 // GIVEN58 const ctx = prepareContext({}, TEST_NOW)59 // WHEN60 stopTask(ctx)('13:37')61 // THEN62 assertStdOut(ctx, `Task stopped at 13:37.\n`)63 assertState(ctx, {64 days: {65 "1981-07-23": [66 "13:37|stop"67 ]68 }69 })70 })71 })72 describe('status', () => {73 it('no running task for empty entries', () => {74 // GIVEN75 const ctx = prepareContext({}, TEST_NOW)76 // WHEN77 showStatus(ctx)()78 assertStdOut(ctx, 'No task is running.\n')79 })80 it('no running task if last entry is stop', () => {81 // GIVEN82 const ctx = prepareContext({83 days: {84 "1981-07-23": [85 "11:30|start|eat",86 "12:20|stop"87 ]88 }89 }, TEST_NOW)90 // WHEN91 showStatus(ctx)()92 // THEN93 assertStdOut(ctx, 'No task is running.\n')94 })95 it('last task shown as running', () => {96 // GIVEN97 const ctx = prepareContext({98 days: {99 "1981-07-23": [100 "11:30|start|eat",101 "12:30|start|drink"102 ]103 }104 }, TEST_NOW)105 // WHEN106 showStatus(ctx)()107 // THEN108 assertStdOut(ctx, "Task 'drink' is running since 12:30.\n")109 })110 })111 describe('report', ()=>{112 it('', ()=>{113 })114 })115 describe('countdown', ()=>{116 it('time to go', ()=>{117 // GIVEN 118 const ctx = prepareContext({119 days: {120 "1981-07-23" : [121 "10:12|start|eat"122 ]123 }124 }, TEST_NOW)125 // WHEN 126 countdown(ctx)()127 // THEN128 assertStdOut(ctx, "Time spent today 01:00\nTime to go 07:00\nYou are finished 18:12\n")129 })130 it('overtime', ()=>{131 // GIVEN 132 const ctx = prepareContext({133 days: {134 "1981-07-23" : [135 "0:12|start|eat"136 ]137 }138 }, TEST_NOW)139 140 // WHEN141 countdown(ctx)()142 // THEN143 assertStdOut(ctx, "Time spent today 11:00\nOvertime 03:00\nYou were finished 08:12\n")144 })145 it('scope week', ()=>{146 // GIVEN 147 const ctx = prepareContext({148 days: {149 "1981-07-23" : [150 "0:12|start|eat"151 ]152 }153 }, TEST_NOW)154 // WHEN 155 countdown(ctx)('week')156 // THEN157 assertStdOut(ctx, "Time spent this week 11:00\nTime to go 29:00\n")158 })159 })...
ABQLRowPluck.js
Source:ABQLRowPluck.js
1const ABQLRowPluckCore = require("../../core/ql/ABQLRowPluckCore.js");2const ABQLSetPluck = require("./ABQLSetPluck.js");3class ABQLRowPluck extends ABQLRowPluckCore {4 /**5 * do()6 * perform the action for this Query Language Operation.7 * @param {Promise} chain8 * The incoming Promise that we need to extend and use to perform9 * our action.10 * @param {obj} instance11 * The current process instance values used by our tasks to store12 * their state/values.13 * @param {Knex.Transaction?} trx14 * (optional) Knex Transaction instance.15 * @param {ABUtil.reqService} req16 * an instance of the current request object for performing tenant17 * based operations.18 * @return {Promise}19 */20 do(chain, instance, trx, req) {21 let nextLink = chain.then((context) => {22 return (23 Promise.resolve()24 // Reuse a pluck data function from ABQLSetPluck25 .then(() => {26 let prepareChain = new Promise((next) => {27 let prepareContext = {28 object: context.object,29 data: context.data,30 prev: context,31 };32 // convert to an array33 if (34 prepareContext.data != null &&35 !Array.isArray(prepareContext.data)36 )37 prepareContext.data = [prepareContext.data];38 next(prepareContext);39 });40 // NOTE: Use new ABQLSetPluck instance because ignore call this.next.do function to mess up the chain variable41 let setPluck = new ABQLSetPluck(42 {43 fieldID: this.fieldID,44 },45 this,46 null,47 this.AB48 );49 setPluck.object = this.object;50 return setPluck.do(prepareChain, instance, trx, req);51 })52 // change label from "ABQLSetPluck" to "ABQLRowPluck"53 .then((context) => {54 let nextContext = this.AB.clone(context);55 nextContext.label = "ABQLRowPluck";56 // Clean up the data to match the pluck field57 if (nextContext.data) {58 // If the pluck field is the M:N, M:1 connect field, then it should pass an array data59 if (60 this.fieldID != "_PK" &&61 this.field.key == "connectObject" &&62 this.field.settings.linkType == "many"63 ) {64 // Convert to an array65 if (!Array.isArray(nextContext.data))66 nextContext.data = [nextContext.data];67 }68 // Normal field should pass a single object value69 else if (Array.isArray(nextContext.data)) {70 if (nextContext.data.length > 1) {71 this.process.log(72 `The data values have more than 1. "${this.field.columnName}" does not support multiple values.`73 );74 nextContext.data = nextContext.data[0];75 } else if (nextContext.data.length == 1) {76 nextContext.data = nextContext.data[0];77 } else if (nextContext.data.length < 1) {78 nextContext.data = null;79 }80 }81 }82 return nextContext;83 })84 );85 });86 if (this.next) {87 return this.next.do(nextLink, instance, trx, req);88 } else {89 return nextLink;90 }91 }92}...
routes-plugin.js
Source:routes-plugin.js
1/*2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.3 *4 * Licensed under the Apache License, Version 2.0 (the "License").5 * You may not use this file except in compliance with the License.6 * A copy of the License is located at7 *8 * http://aws.amazon.com/apache2.09 *10 * or in the "license" file accompanying this file. This file is distributed11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either12 * express or implied. See the License for the specific language governing13 * permissions and limitations under the License.14 */15const setupAuthContext = require('@aws-ee/base-controllers/dist/middlewares/setup-auth-context');16const prepareContext = require('@aws-ee/base-controllers/dist/middlewares/prepare-context');17const ensureActive = require('@aws-ee/base-controllers/dist/middlewares/ensure-active');18const appstreamImagesController = require('../controllers/appstream-images-controller');19const appstreamImageBuildersController = require('../controllers/appstream-image-builders-controller');20const appstreamApplicationsController = require('../controllers/appstream-applications-controller');21const appstreamFleetsController = require('../controllers/appstream-fleets-controller');22const dynamicCatalogsController = require('../controllers/dynamic-catalogs-controller');23const groupsController = require('../controllers/groups-controller');24const metricsController = require('../controllers/metrics-controller');25/**26 * Adds routes to the given routesMap.27 *28 * @param routesMap A Map containing routes. This object is a Map that has route paths as29 * keys and an array of functions that configure the router as value. Each function in the30 * array is expected have the following signature. The function accepts context and router31 * arguments and returns a configured router.32 *33 * (context, router) => configured router34 *35 * @param pluginRegistry A registry that provides plugins registered by various addons for the specified extension point.36 *37 * @returns {Promise<*>} Returns a Map with the mapping of the routes vs their router configurer functions38 */39// eslint-disable-next-line no-unused-vars40async function getRoutes(routesMap, pluginRegistry) {41 const routes = new Map([42 ...routesMap,43 // PROTECTED APIS accessible only to logged in active users44 ['/api/appstream-images', [setupAuthContext, prepareContext, ensureActive, appstreamImagesController]],45 [46 '/api/appstream-image-builders',47 [setupAuthContext, prepareContext, ensureActive, appstreamImageBuildersController],48 ],49 ['/api/appstream-applications', [setupAuthContext, prepareContext, ensureActive, appstreamApplicationsController]],50 ['/api/appstream-fleets', [setupAuthContext, prepareContext, ensureActive, appstreamFleetsController]],51 ['/api/dynamic-catalogs', [setupAuthContext, prepareContext, ensureActive, dynamicCatalogsController]],52 ['/api/groups', [setupAuthContext, prepareContext, ensureActive, groupsController]],53 ['/api/metrics', [setupAuthContext, prepareContext, ensureActive, metricsController]],54 ]);55 return routes;56}57const plugin = {58 getRoutes,59};...
canvases.js
Source:canvases.js
...6 var defaultWidth = 0;7 var defaultHeight = 0;8 var outputCanvas = document.getElementById('output_full');9 canvases.output = outputCanvas;10 contexts.output = prepareContext(outputCanvas.getContext('2d'));11 function prepareContext(context) {12 context.imageSmoothingEnabled = false;13 context.mozImageSmoothingEnabled = false;14 return context;15 }16 function create(name, canvasSet, contextSet) {17 var canvas = document.createElement('canvas');18 if (canvasSet === canvases) {19 canvas.height = defaultHeight * settings.scales[name];20 canvas.width = defaultWidth * settings.scales[name];21 }22 (canvases || canvasSet)[name] = canvas;23 (contexts || contextSet)[name] = canvas.getContext('2d');24 }25 return {26 getCanvas: function(name, setName) {27 var canvasSet = canvases;28 var contextSet = contexts;29 if (setName) {30 if (!sets[setName]) sets[setName] = {canvases: {}, contexts: {}};31 canvasSet = sets[setName].canvases;32 contextSet = sets[setName].contexts;33 }34 if (!(name in canvasSet)) create(name, canvasSet, contextSet);35 return canvasSet[name];36 },37 getContext: function(name, setName) {38 var canvasSet = canvases;39 var contextSet = contexts;40 if (setName) {41 if (!sets[setName]) sets[setName] = {canvases: {}, contexts: {}};42 canvasSet = sets[setName].canvases;43 contextSet = sets[setName].contexts;44 }45 if (!(name in contextSet)) create(name, canvasSet, contextSet);46 return prepareContext(contextSet[name]);47 },48 setSizes: function(width, height) {49 defaultWidth = width;50 defaultHeight = height;51 for (var c in canvases) {52 if (c === 'output') continue; // Don't scale output53 canvases[c].height = height * settings.scales[c];54 canvases[c].width = width * settings.scales[c];55 }56 },57 prepareContext: prepareContext58 };...
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1Cypress.Commands.add('prepareContext', () => {2 cy.window().then((win) => {3 cy.spy(win.console, 'log').as('consoleLog');4 });5});6Cypress.Commands.add('assertContext', (context) => {7 cy.get('@consoleLog').should('be.calledWith', context);8});9Cypress.Commands.add('prepareContext', () => {10 cy.window().then((win) => {11 cy.spy(win.console, 'log').as('consoleLog');12 });13});14Cypress.Commands.add('assertContext', (context) => {15 cy.get('@consoleLog').should('be.calledWith', context);16});17Cypress.Commands.add('prepareContext', () => {18 cy.window().then((win) => {19 cy.spy(win.console, 'log').as('consoleLog');20 });21});22Cypress.Commands.add('assertContext', (context) => {23 cy.get('@consoleLog').should('be.calledWith', context);24});25Cypress.Commands.add('prepareContext', () => {26 cy.window().then((win) => {27 cy.spy(win.console, 'log').as('consoleLog');28 });29});30Cypress.Commands.add('assertContext', (context) => {31 cy.get('@consoleLog').should('be.calledWith', context);32});33Cypress.Commands.add('prepareContext', () => {34 cy.window().then((win) => {35 cy.spy(win.console, 'log').as('consoleLog');36 });37});38Cypress.Commands.add('assertContext', (context) => {39 cy.get('@consoleLog').should('be.calledWith', context);40});41Cypress.Commands.add('prepareContext', () => {42 cy.window().then((win) => {43 cy.spy(win.console, 'log').as('consoleLog
Using AI Code Generation
1import { prepareContext } from 'cypress-angular-unit-test';2describe('MyComponent', () => {3 beforeEach(() => {4 prepareContext(MyComponent);5 });6});7This library is not compatible with Angular Universal. If you want to test your components in a Universal environment, you should use [cypress-angular-unit-test-universal](
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!