How to use model method in Playwright Internal

Best JavaScript code snippet using playwright-internal

AnimationViewModelSpec.js

Source:AnimationViewModelSpec.js Github

copy

Full Screen

1defineSuite([2 'Widgets/Animation/AnimationViewModel',3 'Core/ClockRange',4 'Core/ClockStep',5 'Core/JulianDate',6 'Widgets/ClockViewModel'7 ], function(8 AnimationViewModel,9 ClockRange,10 ClockStep,11 JulianDate,12 ClockViewModel) {13 'use strict';1415 var clockViewModel;16 beforeEach(function() {17 clockViewModel = new ClockViewModel();18 });1920 function verifyPausedState(viewModel) {21 expect(viewModel.pauseViewModel.toggled).toEqual(true);22 expect(viewModel.playReverseViewModel.toggled).toEqual(false);23 expect(viewModel.playForwardViewModel.toggled).toEqual(false);24 expect(viewModel.playRealtimeViewModel.toggled).toEqual(false);25 }2627 function verifyForwardState(viewModel) {28 expect(viewModel.pauseViewModel.toggled).toEqual(false);29 expect(viewModel.playReverseViewModel.toggled).toEqual(false);30 expect(viewModel.playForwardViewModel.toggled).toEqual(true);31 expect(viewModel.playRealtimeViewModel.toggled).toEqual(false);32 }3334 function verifyReverseState(viewModel) {35 expect(viewModel.pauseViewModel.toggled).toEqual(false);36 expect(viewModel.playReverseViewModel.toggled).toEqual(true);37 expect(viewModel.playForwardViewModel.toggled).toEqual(false);38 expect(viewModel.playRealtimeViewModel.toggled).toEqual(false);39 }4041 function verifyRealtimeState(viewModel) {42 expect(viewModel.pauseViewModel.toggled).toEqual(false);43 expect(viewModel.playReverseViewModel.toggled).toEqual(false);44 expect(viewModel.playForwardViewModel.toggled).toEqual(false);45 expect(viewModel.playRealtimeViewModel.toggled).toEqual(true);46 expect(viewModel.shuttleRingAngle).toEqual(AnimationViewModel._realtimeShuttleRingAngle);47 }4849 it('constructor sets expected properties', function() {50 var animationViewModel = new AnimationViewModel(clockViewModel);51 expect(animationViewModel.clockViewModel).toBe(clockViewModel);52 });5354 it('setTimeFormatter overrides the default formatter', function() {55 var animationViewModel = new AnimationViewModel(clockViewModel);5657 var expectedString = 'My Time';58 var myCustomFormatter = function(date) {59 expect(date).toEqual(clockViewModel.currentTime);60 return expectedString;61 };62 animationViewModel.timeFormatter = myCustomFormatter;6364 expect(animationViewModel.timeLabel).toEqual(expectedString);65 expect(animationViewModel.timeFormatter).toEqual(myCustomFormatter);66 });6768 it('defaultTimeFormatter produces expected result', function() {69 var animationViewModel = new AnimationViewModel(clockViewModel);7071 var date = JulianDate.fromIso8601('2012-03-05T06:07:08.89Z');7273 clockViewModel.multiplier = 1;74 var expectedResult = '06:07:08 UTC';75 var result = animationViewModel.timeFormatter(date, animationViewModel);76 expect(result).toEqual(expectedResult);7778 clockViewModel.multiplier = -1;79 expectedResult = '06:07:08 UTC';80 result = animationViewModel.timeFormatter(date, animationViewModel);81 expect(result).toEqual(expectedResult);8283 clockViewModel.multiplier = -0.5;84 expectedResult = '06:07:08.890';85 result = animationViewModel.timeFormatter(date, animationViewModel);86 expect(result).toEqual(expectedResult);8788 clockViewModel.multiplier = 0.5;89 expectedResult = '06:07:08.890';90 result = animationViewModel.timeFormatter(date, animationViewModel);91 expect(result).toEqual(expectedResult);92 });9394 it('setDateFormatter overrides the default formatter', function() {95 var animationViewModel = new AnimationViewModel(clockViewModel);9697 var expectedString = 'My Date';98 var myCustomFormatter = function(date) {99 expect(date).toEqual(clockViewModel.currentTime);100 return expectedString;101 };102 animationViewModel.dateFormatter = myCustomFormatter;103104 expect(animationViewModel.dateLabel).toEqual(expectedString);105 expect(animationViewModel.dateFormatter).toEqual(myCustomFormatter);106 });107108 it('defaultDateFormatter produces expected result', function() {109 var animationViewModel = new AnimationViewModel(new ClockViewModel());110111 var date = JulianDate.fromIso8601('2012-01-05T06:07:08.89Z');112 var expectedResult = 'Jan 5 2012';113 var result = animationViewModel.dateFormatter(date, animationViewModel);114 expect(result).toEqual(expectedResult);115116 date = JulianDate.fromIso8601('2012-02-05T06:07:08.89Z');117 expectedResult = 'Feb 5 2012';118 result = animationViewModel.dateFormatter(date, animationViewModel);119 expect(result).toEqual(expectedResult);120121 date = JulianDate.fromIso8601('2012-03-05T06:07:08.89Z');122 expectedResult = 'Mar 5 2012';123 result = animationViewModel.dateFormatter(date, animationViewModel);124 expect(result).toEqual(expectedResult);125126 date = JulianDate.fromIso8601('2012-04-05T06:07:08.89Z');127 expectedResult = 'Apr 5 2012';128 result = animationViewModel.dateFormatter(date, animationViewModel);129 expect(result).toEqual(expectedResult);130131 date = JulianDate.fromIso8601('2012-05-05T06:07:08.89Z');132 expectedResult = 'May 5 2012';133 result = animationViewModel.dateFormatter(date, animationViewModel);134 expect(result).toEqual(expectedResult);135136 date = JulianDate.fromIso8601('2012-06-05T06:07:08.89Z');137 expectedResult = 'Jun 5 2012';138 result = animationViewModel.dateFormatter(date, animationViewModel);139 expect(result).toEqual(expectedResult);140141 date = JulianDate.fromIso8601('2012-07-05T06:07:08.89Z');142 expectedResult = 'Jul 5 2012';143 result = animationViewModel.dateFormatter(date, animationViewModel);144 expect(result).toEqual(expectedResult);145146 date = JulianDate.fromIso8601('2012-08-05T06:07:08.89Z');147 expectedResult = 'Aug 5 2012';148 result = animationViewModel.dateFormatter(date, animationViewModel);149 expect(result).toEqual(expectedResult);150151 date = JulianDate.fromIso8601('2012-09-05T06:07:08.89Z');152 expectedResult = 'Sep 5 2012';153 result = animationViewModel.dateFormatter(date, animationViewModel);154 expect(result).toEqual(expectedResult);155156 date = JulianDate.fromIso8601('2012-10-05T06:07:08.89Z');157 expectedResult = 'Oct 5 2012';158 result = animationViewModel.dateFormatter(date, animationViewModel);159 expect(result).toEqual(expectedResult);160161 date = JulianDate.fromIso8601('2012-11-05T06:07:08.89Z');162 expectedResult = 'Nov 5 2012';163 result = animationViewModel.dateFormatter(date, animationViewModel);164 expect(result).toEqual(expectedResult);165166 date = JulianDate.fromIso8601('2012-12-05T06:07:08.89Z');167 expectedResult = 'Dec 5 2012';168 result = animationViewModel.dateFormatter(date, animationViewModel);169 expect(result).toEqual(expectedResult);170 });171172 it('correctly formats speed label', function() {173 var animationViewModel = new AnimationViewModel(clockViewModel);174 var expectedString;175176 clockViewModel.clockStep = ClockStep.TICK_DEPENDENT;177 clockViewModel.multiplier = 123.1;178 expectedString = '123.1x';179 expect(animationViewModel.multiplierLabel).toEqual(expectedString);180181 clockViewModel.clockStep = ClockStep.TICK_DEPENDENT;182 clockViewModel.multiplier = 123.12;183 expectedString = '123.12x';184 expect(animationViewModel.multiplierLabel).toEqual(expectedString);185186 clockViewModel.clockStep = ClockStep.TICK_DEPENDENT;187 clockViewModel.multiplier = 123.123;188 expectedString = '123.123x';189 expect(animationViewModel.multiplierLabel).toEqual(expectedString);190191 clockViewModel.clockStep = ClockStep.TICK_DEPENDENT;192 clockViewModel.multiplier = 123.1236;193 expectedString = '123.124x';194 expect(animationViewModel.multiplierLabel).toEqual(expectedString);195196 clockViewModel.clockStep = ClockStep.SYSTEM_CLOCK;197 expectedString = 'Today';198 expect(animationViewModel.multiplierLabel).toEqual(expectedString);199200 clockViewModel.clockStep = ClockStep.TICK_DEPENDENT;201 clockViewModel.multiplier = 15;202 expectedString = '15x';203 expect(animationViewModel.multiplierLabel).toEqual(expectedString);204 });205206 it('pause button restores current state', function() {207 clockViewModel.startTime = JulianDate.fromIso8601("2012-01-01T00:00:00");208 clockViewModel.stopTime = JulianDate.fromIso8601("2012-01-02T00:00:00");209 clockViewModel.currentTime = JulianDate.fromIso8601("2012-01-01T12:00:00");210 clockViewModel.multiplier = 1;211 clockViewModel.clockStep = ClockStep.TICK_DEPENDENT;212 clockViewModel.clockRange = ClockRange.UNBOUNDED;213 clockViewModel.shouldAnimate = false;214215 var viewModel = new AnimationViewModel(clockViewModel);216217 //Starts out paused218 verifyPausedState(viewModel);219220 //Toggling paused restores state when animating forward221 viewModel.pauseViewModel.command();222223 verifyForwardState(viewModel);224225 //Executing paused command restores paused state226 viewModel.pauseViewModel.command();227228 verifyPausedState(viewModel);229230 //Setting the multiplier to negative and unpausing animates backward231 clockViewModel.multiplier = -1;232 viewModel.pauseViewModel.command();233234 verifyReverseState(viewModel);235 });236237 it('animating forwards negates the multiplier if it is negative', function() {238 var viewModel = new AnimationViewModel(clockViewModel);239 var multiplier = -100;240 clockViewModel.multiplier = multiplier;241 viewModel.playForwardViewModel.command();242 expect(clockViewModel.multiplier).toEqual(-multiplier);243 });244245 it('animating backwards negates the multiplier if it is positive', function() {246 var viewModel = new AnimationViewModel(clockViewModel);247 var multiplier = 100;248 clockViewModel.multiplier = multiplier;249 viewModel.playReverseViewModel.command();250 expect(clockViewModel.multiplier).toEqual(-multiplier);251 });252253 it('animating backwards pauses with a bounded startTime', function() {254 var centerTime = JulianDate.fromIso8601("2012-01-01T12:00:00");255256 clockViewModel.startTime = JulianDate.fromIso8601("2012-01-01T00:00:00");257 clockViewModel.stopTime = JulianDate.fromIso8601("2012-01-02T00:00:00");258 clockViewModel.clockStep = ClockStep.TICK_DEPENDENT;259 clockViewModel.currentTime = centerTime;260 clockViewModel.shouldAnimate = false;261262 var viewModel = new AnimationViewModel(clockViewModel);263 verifyPausedState(viewModel);264265 //Play in reverse while clamped266 clockViewModel.multiplier = -1;267 clockViewModel.clockRange = ClockRange.CLAMPED;268 viewModel.playReverseViewModel.command();269270 verifyReverseState(viewModel);271272 //Set current time to start time273 clockViewModel.currentTime = clockViewModel.startTime;274275 //Should now be paused276 verifyPausedState(viewModel);277278 //Animate in reverse again.279 clockViewModel.currentTime = centerTime;280 clockViewModel.clockRange = ClockRange.LOOP_STOP;281 viewModel.playReverseViewModel.command();282283 verifyReverseState(viewModel);284285 //Set current time to start time286 clockViewModel.currentTime = clockViewModel.startTime;287288 //Should now be paused289 verifyPausedState(viewModel);290291 //Reversing in start state while bounded should have no effect292 viewModel.playReverseViewModel.command();293 verifyPausedState(viewModel);294295 //Set to unbounded and reversing should be okay296 clockViewModel.clockRange = ClockRange.UNBOUNDED;297 viewModel.playReverseViewModel.command();298 verifyReverseState(viewModel);299 });300301 it('dragging shuttle ring does not pause with bounded start or stop Time', function() {302 var centerTime = JulianDate.fromIso8601("2012-01-01T12:00:00");303304 clockViewModel.startTime = JulianDate.fromIso8601("2012-01-01T00:00:00");305 clockViewModel.stopTime = JulianDate.fromIso8601("2012-01-02T00:00:00");306 clockViewModel.clockStep = ClockStep.TICK_DEPENDENT;307 clockViewModel.clockRange = ClockRange.CLAMPED;308 clockViewModel.multiplier = 1;309310 var viewModel = new AnimationViewModel(clockViewModel);311 verifyPausedState(viewModel);312313 //Play forward while clamped314 clockViewModel.currentTime = centerTime;315 viewModel.playForwardViewModel.command();316 verifyForwardState(viewModel);317318 //Set current time to stop time, which won't stop while dragging319 viewModel.shuttleRingDragging = true;320 clockViewModel.currentTime = clockViewModel.stopTime;321 verifyForwardState(viewModel);322323 //Drag complete stops.324 viewModel.shuttleRingDragging = false;325 verifyPausedState(viewModel);326327 //Do the same thing with start time328 clockViewModel.currentTime = centerTime;329 viewModel.playReverseViewModel.command();330 verifyReverseState(viewModel);331332 viewModel.shuttleRingDragging = true;333 clockViewModel.currentTime = clockViewModel.startTime;334 verifyReverseState(viewModel);335336 //Drag complete stops.337 viewModel.shuttleRingDragging = false;338 verifyPausedState(viewModel);339 });340341 it('animating forward pauses with a bounded stopTime', function() {342 var centerTime = JulianDate.fromIso8601("2012-01-01T12:00:00");343344 clockViewModel.startTime = JulianDate.fromIso8601("2012-01-01T00:00:00");345 clockViewModel.stopTime = JulianDate.fromIso8601("2012-01-02T00:00:00");346 clockViewModel.clockStep = ClockStep.TICK_DEPENDENT;347 clockViewModel.currentTime = centerTime;348 clockViewModel.shouldAnimate = false;349350 var viewModel = new AnimationViewModel(clockViewModel);351 verifyPausedState(viewModel);352353 //Play forward while clamped354 clockViewModel.multiplier = 1;355 clockViewModel.clockRange = ClockRange.CLAMPED;356 viewModel.playForwardViewModel.command();357358 verifyForwardState(viewModel);359360 //Set current time to stop time361 clockViewModel.currentTime = clockViewModel.stopTime;362363 //Should now be paused364 verifyPausedState(viewModel);365366 //Playing in stop state while bounded should have no effect367 viewModel.playForwardViewModel.command();368 verifyPausedState(viewModel);369370 //Set to unbounded and playing should be okay371 clockViewModel.clockRange = ClockRange.UNBOUNDED;372 viewModel.playForwardViewModel.command();373 verifyForwardState(viewModel);374 });375376 it('slower has no effect if at the slowest speed', function() {377 var viewModel = new AnimationViewModel(clockViewModel);378 viewModel.setShuttleRingTicks([0.0, 1.0, 2.0]);379 var slowestMultiplier = -2;380 clockViewModel.multiplier = slowestMultiplier;381 viewModel.slower();382 expect(clockViewModel.multiplier).toEqual(slowestMultiplier);383 });384385 it('faster has no effect if at the faster speed', function() {386 var viewModel = new AnimationViewModel(clockViewModel);387 viewModel.setShuttleRingTicks([0.0, 1.0, 2.0]);388 var fastestMultiplier = 2;389 clockViewModel.multiplier = fastestMultiplier;390 viewModel.faster();391 expect(clockViewModel.multiplier).toEqual(fastestMultiplier);392 });393394 it('slower and faster cycle through defined multipliers', function() {395 var viewModel = new AnimationViewModel(clockViewModel);396397 var i = 0;398 var multipliers = viewModel.getShuttleRingTicks();399 var length = multipliers.length;400401 //Start at slowest speed402 clockViewModel.multiplier = multipliers[0];403404 //Cycle through them all with faster405 for (i = 1; i < length; i++) {406 viewModel.faster();407 expect(clockViewModel.multiplier).toEqual(multipliers[i]);408 }409410 //We should be at the fastest time now.411 expect(clockViewModel.multiplier).toEqual(multipliers[length - 1]);412413 //Cycle through them all with slower414 for (i = length - 2; i >= 0; i--) {415 viewModel.slower();416 expect(clockViewModel.multiplier).toEqual(multipliers[i]);417 }418419 //We should be at the slowest time now.420 expect(clockViewModel.multiplier).toEqual(multipliers[0]);421 });422423 it('Realtime canExecute and tooltip depends on clock settings', function() {424 var viewModel = new AnimationViewModel(clockViewModel);425426 //UNBOUNDED but available when start/stop time does not include realtime427 clockViewModel.systemTime = JulianDate.now();428 clockViewModel.clockRange = ClockRange.UNBOUNDED;429 clockViewModel.startTime = JulianDate.addSeconds(clockViewModel.systemTime, -60, new JulianDate());430 clockViewModel.stopTime = JulianDate.addSeconds(clockViewModel.systemTime, -30, new JulianDate());431 expect(viewModel.playRealtimeViewModel.command.canExecute).toEqual(true);432 expect(viewModel.playRealtimeViewModel.tooltip).toEqual('Today (real-time)');433434 //CLAMPED but unavailable when start/stop time does not include realtime435 clockViewModel.clockRange = ClockRange.CLAMPED;436 clockViewModel.startTime = JulianDate.addSeconds(clockViewModel.systemTime, -60, new JulianDate());437 clockViewModel.stopTime = JulianDate.addSeconds(clockViewModel.systemTime, -30, new JulianDate());438 expect(viewModel.playRealtimeViewModel.command.canExecute).toEqual(false);439 expect(viewModel.playRealtimeViewModel.tooltip).toEqual('Current time not in range');440441 //CLAMPED but available when start/stop time includes realtime442 clockViewModel.clockRange = ClockRange.CLAMPED;443 clockViewModel.startTime = JulianDate.addSeconds(clockViewModel.systemTime, -60, new JulianDate());444 clockViewModel.stopTime = JulianDate.addSeconds(clockViewModel.systemTime, 60, new JulianDate());445 expect(viewModel.playRealtimeViewModel.command.canExecute).toEqual(true);446 expect(viewModel.playRealtimeViewModel.tooltip).toEqual('Today (real-time)');447448 //LOOP_STOP but unavailable when start/stop time does not include realtime449 clockViewModel.clockRange = ClockRange.LOOP_STOP;450 clockViewModel.startTime = JulianDate.addSeconds(clockViewModel.systemTime, -60, new JulianDate());451 clockViewModel.stopTime = JulianDate.addSeconds(clockViewModel.systemTime, -30, new JulianDate());452 expect(viewModel.playRealtimeViewModel.command.canExecute).toEqual(false);453 expect(viewModel.playRealtimeViewModel.tooltip).toEqual('Current time not in range');454455 //LOOP_STOP but available when start/stop time includes realtime456 clockViewModel.clockRange = ClockRange.LOOP_STOP;457 clockViewModel.startTime = JulianDate.addSeconds(clockViewModel.systemTime, -60, new JulianDate());458 clockViewModel.stopTime = JulianDate.addSeconds(clockViewModel.systemTime, 60, new JulianDate());459 expect(viewModel.playRealtimeViewModel.command.canExecute).toEqual(true);460 expect(viewModel.playRealtimeViewModel.tooltip).toEqual('Today (real-time)');461 });462463 it('User action breaks out of realtime mode', function() {464 var viewModel = new AnimationViewModel(clockViewModel);465 clockViewModel.clockStep = ClockStep.TICK_DEPENDENT;466 clockViewModel.clockRange = ClockRange.UNBOUNDED;467468 viewModel.playRealtimeViewModel.command();469 verifyRealtimeState(viewModel);470 expect(clockViewModel.multiplier).toEqual(1);471472 //Pausing breaks realtime state473 viewModel.pauseViewModel.command();474 verifyPausedState(viewModel);475 expect(clockViewModel.multiplier).toEqual(1);476477 viewModel.playRealtimeViewModel.command();478 verifyRealtimeState(viewModel);479480 //Reverse breaks realtime state481 viewModel.playReverseViewModel.command();482 verifyReverseState(viewModel);483 expect(clockViewModel.multiplier).toEqual(-1);484485 viewModel.playRealtimeViewModel.command();486 verifyRealtimeState(viewModel);487488 //Play does not break realtime state489 viewModel.playForwardViewModel.command();490 verifyRealtimeState(viewModel);491 expect(clockViewModel.multiplier).toEqual(1);492493 viewModel.playRealtimeViewModel.command();494 verifyRealtimeState(viewModel);495496 //Shuttle ring change breaks realtime state497 viewModel.shuttleRingAngle = viewModel.shuttleRingAngle + 1;498 verifyForwardState(viewModel);499 });500501 it('real time mode toggles off but not back on when shouldAnimate changes', function() {502 var viewModel = new AnimationViewModel(clockViewModel);503504 viewModel.playRealtimeViewModel.command();505 verifyRealtimeState(viewModel);506507 clockViewModel.shouldAnimate = false;508 expect(viewModel.playRealtimeViewModel.toggled).toEqual(false);509510 clockViewModel.shouldAnimate = true;511 expect(viewModel.playRealtimeViewModel.toggled).toEqual(false);512 });513514 it('Shuttle ring angles set expected multipliers', function() {515 var viewModel = new AnimationViewModel(clockViewModel);516517 var shuttleRingTicks = viewModel.getShuttleRingTicks();518 var maxMultiplier = shuttleRingTicks[shuttleRingTicks.length - 1];519 var minMultiplier = -maxMultiplier;520521 //Max angle should produce max speed522 viewModel.shuttleRingAngle = AnimationViewModel._maxShuttleRingAngle;523 expect(clockViewModel.multiplier).toEqual(maxMultiplier);524525 //Min angle should produce min speed526 viewModel.shuttleRingAngle = -AnimationViewModel._maxShuttleRingAngle;527 expect(clockViewModel.multiplier).toEqual(minMultiplier);528529 //AnimationViewModel._realtimeShuttleRingAngle degrees is always 1x530 viewModel.shuttleRingAngle = AnimationViewModel._realtimeShuttleRingAngle;531 expect(clockViewModel.multiplier).toEqual(1);532533 viewModel.shuttleRingAngle = -AnimationViewModel._realtimeShuttleRingAngle;534 expect(clockViewModel.multiplier).toEqual(-1);535536 //For large values, the shuttleRingAngle should always round to the first two digits.537 viewModel.shuttleRingAngle = 45.0;538 expect(clockViewModel.multiplier).toEqual(85.0);539540 viewModel.shuttleRingAngle = -90.0;541 expect(clockViewModel.multiplier).toEqual(-66000.0);542543 viewModel.shuttleRingAngle = 0.0;544 expect(clockViewModel.multiplier).toEqual(0.0);545 });546547 it('Shuttle ring angles set expected multipliers when snapping to ticks', function() {548 var viewModel = new AnimationViewModel(clockViewModel);549 viewModel.snapToTicks = true;550551 var shuttleRingTicks = viewModel.getShuttleRingTicks();552 var maxMultiplier = shuttleRingTicks[shuttleRingTicks.length - 1];553 var minMultiplier = -maxMultiplier;554555 //Max angle should produce max speed556 viewModel.shuttleRingAngle = AnimationViewModel._maxShuttleRingAngle;557 expect(clockViewModel.multiplier).toEqual(maxMultiplier);558559 //Min angle should produce min speed560 viewModel.shuttleRingAngle = -AnimationViewModel._maxShuttleRingAngle;561 expect(clockViewModel.multiplier).toEqual(minMultiplier);562563 //AnimationViewModel._realtimeShuttleRingAngle degrees is always 1x564 viewModel.shuttleRingAngle = AnimationViewModel._realtimeShuttleRingAngle;565 expect(clockViewModel.multiplier).toEqual(1);566567 viewModel.shuttleRingAngle = -AnimationViewModel._realtimeShuttleRingAngle;568 expect(clockViewModel.multiplier).toEqual(-1);569570 //For large values, the shuttleRingAngle should always round to the first two digits.571 viewModel.shuttleRingAngle = 45.0;572 expect(clockViewModel.multiplier).toEqual(120.0);573574 viewModel.shuttleRingAngle = -90.0;575 expect(clockViewModel.multiplier).toEqual(-43200.0);576577 viewModel.shuttleRingAngle = 0.0;578 expect(clockViewModel.multiplier).toEqual(AnimationViewModel.defaultTicks[0]);579 });580581 it('throws when constructed without arguments', function() {582 expect(function() {583 return new AnimationViewModel();584 }).toThrowDeveloperError();585 });586587 it('setting timeFormatter throws with non-function', function() {588 var animationViewModel = new AnimationViewModel(clockViewModel);589 expect(function() {590 animationViewModel.timeFormatter = {};591 }).toThrowDeveloperError();592 });593594 it('setting dateFormatter throws with non-function', function() {595 var animationViewModel = new AnimationViewModel(clockViewModel);596 expect(function() {597 animationViewModel.dateFormatter = {};598 }).toThrowDeveloperError();599 });600601 it('setting shuttleRingTicks throws with undefined', function() {602 var animationViewModel = new AnimationViewModel(clockViewModel);603 expect(function() {604 animationViewModel.setShuttleRingTicks(undefined);605 }).toThrowDeveloperError();606 });607608 it('returns a copy of shuttleRingTicks when getting', function() {609 var animationViewModel = new AnimationViewModel(clockViewModel);610 var originalTicks = [0.0, 1.0, 2.0];611 animationViewModel.setShuttleRingTicks(originalTicks);612613 var ticks = animationViewModel.getShuttleRingTicks();614 ticks.push(99);615 ticks[0] = -99;616 expect(animationViewModel.getShuttleRingTicks()).toEqual(originalTicks);617 });618619 it('sorts shuttleRingTicks when setting', function() {620 var animationViewModel = new AnimationViewModel(clockViewModel);621 var ticks = [4.0, 0.0, 8.0, 2.0];622623 animationViewModel.setShuttleRingTicks(ticks);624 expect(animationViewModel.getShuttleRingTicks()).toEqual([0.0, 2.0, 4.0, 8.0]);625 }); ...

Full Screen

Full Screen

ModelVisualizer.js

Source:ModelVisualizer.js Github

copy

Full Screen

1define([2 '../Core/AssociativeArray',3 '../Core/BoundingSphere',4 '../Core/Color',5 '../Core/defined',6 '../Core/destroyObject',7 '../Core/DeveloperError',8 '../Core/Matrix4',9 '../Scene/ColorBlendMode',10 '../Scene/HeightReference',11 '../Scene/Model',12 '../Scene/ModelAnimationLoop',13 '../Scene/ShadowMode',14 './BoundingSphereState',15 './Property'16 ], function(17 AssociativeArray,18 BoundingSphere,19 Color,20 defined,21 destroyObject,22 DeveloperError,23 Matrix4,24 ColorBlendMode,25 HeightReference,26 Model,27 ModelAnimationLoop,28 ShadowMode,29 BoundingSphereState,30 Property) {31 'use strict';3233 var defaultScale = 1.0;34 var defaultMinimumPixelSize = 0.0;35 var defaultIncrementallyLoadTextures = true;36 var defaultShadows = ShadowMode.ENABLED;37 var defaultHeightReference = HeightReference.NONE;38 var defaultSilhouetteColor = Color.RED;39 var defaultSilhouetteSize = 0.0;40 var defaultColor = Color.WHITE;41 var defaultColorBlendMode = ColorBlendMode.HIGHLIGHT;42 var defaultColorBlendAmount = 0.5;4344 var modelMatrixScratch = new Matrix4();45 var nodeMatrixScratch = new Matrix4();4647 /**48 * A {@link Visualizer} which maps {@link Entity#model} to a {@link Model}.49 * @alias ModelVisualizer50 * @constructor51 *52 * @param {Scene} scene The scene the primitives will be rendered in.53 * @param {EntityCollection} entityCollection The entityCollection to visualize.54 */55 function ModelVisualizer(scene, entityCollection) {56 //>>includeStart('debug', pragmas.debug);57 if (!defined(scene)) {58 throw new DeveloperError('scene is required.');59 }60 if (!defined(entityCollection)) {61 throw new DeveloperError('entityCollection is required.');62 }63 //>>includeEnd('debug');6465 entityCollection.collectionChanged.addEventListener(ModelVisualizer.prototype._onCollectionChanged, this);6667 this._scene = scene;68 this._primitives = scene.primitives;69 this._entityCollection = entityCollection;70 this._modelHash = {};71 this._entitiesToVisualize = new AssociativeArray();72 this._onCollectionChanged(entityCollection, entityCollection.values, [], []);73 }7475 /**76 * Updates models created this visualizer to match their77 * Entity counterpart at the given time.78 *79 * @param {JulianDate} time The time to update to.80 * @returns {Boolean} This function always returns true.81 */82 ModelVisualizer.prototype.update = function(time) {83 //>>includeStart('debug', pragmas.debug);84 if (!defined(time)) {85 throw new DeveloperError('time is required.');86 }87 //>>includeEnd('debug');8889 var entities = this._entitiesToVisualize.values;90 var modelHash = this._modelHash;91 var primitives = this._primitives;9293 for (var i = 0, len = entities.length; i < len; i++) {94 var entity = entities[i];95 var modelGraphics = entity._model;9697 var uri;98 var modelData = modelHash[entity.id];99 var show = entity.isShowing && entity.isAvailable(time) && Property.getValueOrDefault(modelGraphics._show, time, true);100101 var modelMatrix;102 if (show) {103 modelMatrix = entity.computeModelMatrix(time, modelMatrixScratch);104 uri = Property.getValueOrUndefined(modelGraphics._uri, time);105 show = defined(modelMatrix) && defined(uri);106 }107108 if (!show) {109 if (defined(modelData)) {110 modelData.modelPrimitive.show = false;111 }112 continue;113 }114115 var model = defined(modelData) ? modelData.modelPrimitive : undefined;116 if (!defined(model) || uri !== modelData.uri) {117 if (defined(model)) {118 primitives.removeAndDestroy(model);119 delete modelHash[entity.id];120 }121 model = Model.fromGltf({122 url : uri,123 incrementallyLoadTextures : Property.getValueOrDefault(modelGraphics._incrementallyLoadTextures, time, defaultIncrementallyLoadTextures),124 scene : this._scene125 });126127 model.readyPromise.otherwise(onModelError);128129 model.id = entity;130 primitives.add(model);131132 modelData = {133 modelPrimitive : model,134 uri : uri,135 animationsRunning : false,136 nodeTransformationsScratch : {},137 originalNodeMatrixHash : {}138 };139 modelHash[entity.id] = modelData;140 }141142 model.show = true;143 model.scale = Property.getValueOrDefault(modelGraphics._scale, time, defaultScale);144 model.minimumPixelSize = Property.getValueOrDefault(modelGraphics._minimumPixelSize, time, defaultMinimumPixelSize);145 model.maximumScale = Property.getValueOrUndefined(modelGraphics._maximumScale, time);146 model.modelMatrix = Matrix4.clone(modelMatrix, model.modelMatrix);147 model.shadows = Property.getValueOrDefault(modelGraphics._shadows, time, defaultShadows);148 model.heightReference = Property.getValueOrDefault(modelGraphics._heightReference, time, defaultHeightReference);149 model.distanceDisplayCondition = Property.getValueOrUndefined(modelGraphics._distanceDisplayCondition, time);150 model.silhouetteColor = Property.getValueOrDefault(modelGraphics._silhouetteColor, time, defaultSilhouetteColor, model._silhouetteColor);151 model.silhouetteSize = Property.getValueOrDefault(modelGraphics._silhouetteSize, time, defaultSilhouetteSize);152 model.color = Property.getValueOrDefault(modelGraphics._color, time, defaultColor, model._color);153 model.colorBlendMode = Property.getValueOrDefault(modelGraphics._colorBlendMode, time, defaultColorBlendMode);154 model.colorBlendAmount = Property.getValueOrDefault(modelGraphics._colorBlendAmount, time, defaultColorBlendAmount);155156 if (model.ready) {157 var runAnimations = Property.getValueOrDefault(modelGraphics._runAnimations, time, true);158 if (modelData.animationsRunning !== runAnimations) {159 if (runAnimations) {160 model.activeAnimations.addAll({161 loop : ModelAnimationLoop.REPEAT162 });163 } else {164 model.activeAnimations.removeAll();165 }166 modelData.animationsRunning = runAnimations;167 }168169 // Apply node transformations170 var nodeTransformations = Property.getValueOrUndefined(modelGraphics._nodeTransformations, time, modelData.nodeTransformationsScratch);171 if (defined(nodeTransformations)) {172 var originalNodeMatrixHash = modelData.originalNodeMatrixHash;173 var nodeNames = Object.keys(nodeTransformations);174 for (var nodeIndex = 0, nodeLength = nodeNames.length; nodeIndex < nodeLength; ++nodeIndex) {175 var nodeName = nodeNames[nodeIndex];176177 var nodeTransformation = nodeTransformations[nodeName];178 if (!defined(nodeTransformation)) {179 continue;180 }181182 var modelNode = model.getNode(nodeName);183 if (!defined(modelNode)) {184 continue;185 }186187 var originalNodeMatrix = originalNodeMatrixHash[nodeName];188 if (!defined(originalNodeMatrix)) {189 originalNodeMatrix = modelNode.matrix.clone();190 originalNodeMatrixHash[nodeName] = originalNodeMatrix;191 }192193 var transformationMatrix = Matrix4.fromTranslationRotationScale(nodeTransformation, nodeMatrixScratch);194 modelNode.matrix = Matrix4.multiply(originalNodeMatrix, transformationMatrix, transformationMatrix);195 }196 }197 }198 }199200 return true;201 };202203 /**204 * Returns true if this object was destroyed; otherwise, false.205 *206 * @returns {Boolean} True if this object was destroyed; otherwise, false.207 */208 ModelVisualizer.prototype.isDestroyed = function() {209 return false;210 };211212 /**213 * Removes and destroys all primitives created by this instance.214 */215 ModelVisualizer.prototype.destroy = function() {216 this._entityCollection.collectionChanged.removeEventListener(ModelVisualizer.prototype._onCollectionChanged, this);217 var entities = this._entitiesToVisualize.values;218 var modelHash = this._modelHash;219 var primitives = this._primitives;220 for (var i = entities.length - 1; i > -1; i--) {221 removeModel(this, entities[i], modelHash, primitives);222 }223 return destroyObject(this);224 };225226 /**227 * Computes a bounding sphere which encloses the visualization produced for the specified entity.228 * The bounding sphere is in the fixed frame of the scene's globe.229 *230 * @param {Entity} entity The entity whose bounding sphere to compute.231 * @param {BoundingSphere} result The bounding sphere onto which to store the result.232 * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,233 * BoundingSphereState.PENDING if the result is still being computed, or234 * BoundingSphereState.FAILED if the entity has no visualization in the current scene.235 * @private236 */237 ModelVisualizer.prototype.getBoundingSphere = function(entity, result) {238 //>>includeStart('debug', pragmas.debug);239 if (!defined(entity)) {240 throw new DeveloperError('entity is required.');241 }242 if (!defined(result)) {243 throw new DeveloperError('result is required.');244 }245 //>>includeEnd('debug');246247 var modelData = this._modelHash[entity.id];248 if (!defined(modelData)) {249 return BoundingSphereState.FAILED;250 }251252 var model = modelData.modelPrimitive;253 if (!defined(model) || !model.show) {254 return BoundingSphereState.FAILED;255 }256257 if (!model.ready) {258 return BoundingSphereState.PENDING;259 }260261 if (model.heightReference === HeightReference.NONE) {262 BoundingSphere.transform(model.boundingSphere, model.modelMatrix, result);263 } else {264 if (!defined(model._clampedModelMatrix)) {265 return BoundingSphereState.PENDING;266 }267 BoundingSphere.transform(model.boundingSphere, model._clampedModelMatrix, result);268 }269 return BoundingSphereState.DONE;270 };271272 /**273 * @private274 */275 ModelVisualizer.prototype._onCollectionChanged = function(entityCollection, added, removed, changed) {276 var i;277 var entity;278 var entities = this._entitiesToVisualize;279 var modelHash = this._modelHash;280 var primitives = this._primitives;281282 for (i = added.length - 1; i > -1; i--) {283 entity = added[i];284 if (defined(entity._model) && defined(entity._position)) {285 entities.set(entity.id, entity);286 }287 }288289 for (i = changed.length - 1; i > -1; i--) {290 entity = changed[i];291 if (defined(entity._model) && defined(entity._position)) {292 clearNodeTransformationsScratch(entity, modelHash);293 entities.set(entity.id, entity);294 } else {295 removeModel(this, entity, modelHash, primitives);296 entities.remove(entity.id);297 }298 }299300 for (i = removed.length - 1; i > -1; i--) {301 entity = removed[i];302 removeModel(this, entity, modelHash, primitives);303 entities.remove(entity.id);304 }305 };306307 function removeModel(visualizer, entity, modelHash, primitives) {308 var modelData = modelHash[entity.id];309 if (defined(modelData)) {310 primitives.removeAndDestroy(modelData.modelPrimitive);311 delete modelHash[entity.id];312 }313 }314315 function clearNodeTransformationsScratch(entity, modelHash) {316 var modelData = modelHash[entity.id];317 if (defined(modelData)) {318 modelData.nodeTransformationsScratch = {};319 }320 }321322 function onModelError(error) {323 console.error(error);324 }325326 return ModelVisualizer; ...

Full Screen

Full Screen

abstract.test.js

Source:abstract.test.js Github

copy

Full Screen

1/**2 * Copyright © Magento, Inc. All rights reserved.3 * See COPYING.txt for license details.4 */5/*eslint max-nested-callbacks: 0*/6define([7 'squire'8], function (Squire) {9 'use strict';10 describe('Magento_Ui/js/form/element/abstract', function () {11 var injector = new Squire(),12 providerMock = {13 get: jasmine.createSpy(),14 set: jasmine.createSpy()15 },16 mocks = {17 'Magento_Ui/js/lib/registry/registry': {18 /** Method stub. */19 get: function () {20 return providerMock;21 },22 create: jasmine.createSpy(),23 set: jasmine.createSpy(),24 async: jasmine.createSpy()25 },26 '/mage/utils/wrapper': jasmine.createSpy()27 },28 dataScope = 'abstract',29 params = {30 provider: 'provName',31 name: '',32 index: 'testIndex',33 dataScope: dataScope,34 service: {35 template: 'ui/form/element/helper/service'36 }37 },38 model;39 beforeEach(function (done) {40 injector.mock(mocks);41 injector.require([42 'Magento_Ui/js/form/element/abstract',43 'knockoutjs/knockout-es5'44 ], function (Constr) {45 model = new Constr(params);46 done();47 });48 });49 describe('initialize method', function () {50 it('check for existing', function () {51 expect(model).toBeDefined();52 });53 it('check for chainable', function () {54 spyOn(model, 'setInitialValue').and.returnValue(model);55 spyOn(model, '_setClasses').and.returnValue(model);56 expect(model.initialize(params)).toEqual(model);57 });58 });59 describe('initObservable method', function () {60 it('check for chainable', function () {61 spyOn(model, 'observe').and.returnValue(model);62 expect(model.initObservable()).toEqual(model);63 });64 it('check for validation', function () {65 spyOn(model, 'observe').and.returnValue(model);66 expect(model.initObservable()).toEqual(model);67 expect(model.validation).toEqual({});68 });69 });70 describe('setInitialValue method', function () {71 it('check for chainable', function () {72 expect(model.setInitialValue()).toEqual(model);73 });74 it('check for set value', function () {75 var expectedValue = 1;76 spyOn(model, 'getInitialValue').and.returnValue(expectedValue);77 model.service = true;78 expect(model.setInitialValue()).toEqual(model);79 expect(model.getInitialValue).toHaveBeenCalled();80 expect(model.source.set).toHaveBeenCalledWith('data.use_default.' + model.index, 0);81 expect(model.value()).toEqual(expectedValue);82 });83 });84 describe('_setClasses method', function () {85 it('check for chainable', function () {86 expect(model._setClasses()).toEqual(model);87 });88 it('check for incorrect class set', function () {89 model.additionalClasses = 1;90 expect(model._setClasses()).toEqual(model);91 expect(model.additionalClasses).toEqual(1);92 });93 it('check for empty additional class', function () {94 var expectedResult = {95 _required: model.required,96 _warn: model.warn,97 _error: model.error,98 _disabled: model.disabled99 };100 model.additionalClasses = '';101 expect(model._setClasses()).toEqual(model);102 expect(model.additionalClasses).toEqual(expectedResult);103 });104 it('check for one class in additional', function () {105 var extendObject = {106 simple: true,107 _required: model.required,108 _warn: model.warn,109 _error: model.error,110 _disabled: model.disabled111 };112 model.additionalClasses = 'simple';113 expect(model._setClasses()).toEqual(model);114 expect(model.additionalClasses).toEqual(extendObject);115 });116 it('check for one class with spaces in additional', function () {117 var extendObject = {118 simple: true,119 _required: model.required,120 _warn: model.warn,121 _error: model.error,122 _disabled: model.disabled123 };124 model.additionalClasses = ' simple ';125 expect(model._setClasses()).toEqual(model);126 expect(model.additionalClasses).toEqual(extendObject);127 });128 it('check for multiple classes in additional', function () {129 var extendObject = {130 simple: true,131 example: true,132 _required: model.required,133 _warn: model.warn,134 _error: model.error,135 _disabled: model.disabled136 };137 model.additionalClasses = 'simple example';138 expect(model._setClasses()).toEqual(model);139 expect(model.additionalClasses).toEqual(extendObject);140 });141 it('check for multiple classes with spaces in additional', function () {142 var extendObject = {143 simple: true,144 example: true,145 _required: model.required,146 _warn: model.warn,147 _error: model.error,148 _disabled: model.disabled149 };150 model.additionalClasses = ' simple example ';151 expect(model._setClasses()).toEqual(model);152 expect(model.additionalClasses).toEqual(extendObject);153 });154 });155 describe('getInitialValue method', function () {156 it('check with empty value', function () {157 expect(model.getInitialValue()).toEqual('');158 });159 it('check with default value', function () {160 model.default = 1;161 expect(model.getInitialValue()).toEqual('');162 });163 it('check with value', function () {164 var expected = 1;165 model.value(expected);166 expect(model.getInitialValue()).toEqual(expected);167 });168 it('check with value and default', function () {169 var expected = 1;170 model.default = 2;171 model.value(expected);172 expect(model.getInitialValue()).toEqual(expected);173 });174 });175 describe('setVisible method', function () {176 it('check value by default', function () {177 expect(model.visible()).toBeTruthy();178 });179 it('check for true/false parameters', function () {180 expect(model.setVisible(false)).toEqual(model);181 expect(model.visible()).toBeFalsy();182 expect(model.setVisible(true)).toEqual(model);183 expect(model.visible()).toBeTruthy();184 });185 });186 describe('getPreview method', function () {187 it('check with absent value', function () {188 expect(model.value()).toEqual('');189 });190 it('check with value', function () {191 var expected = 1;192 model.value(expected);193 expect(model.value()).toEqual(expected);194 });195 });196 describe('hasAddons method', function () {197 it('check with absent addbefore and addafter', function () {198 expect(model.hasAddons()).toEqual(undefined);199 });200 it('check with different addbefore and addafter', function () {201 model.addafter = false;202 expect(model.hasAddons()).toEqual(false);203 model.addafter = true;204 expect(model.hasAddons()).toEqual(true);205 model.addbefore = true;206 model.addafter = true;207 expect(model.hasAddons()).toEqual(true);208 model.addbefore = true;209 model.addafter = false;210 expect(model.hasAddons()).toEqual(true);211 model.addbefore = false;212 model.addafter = false;213 expect(model.hasAddons()).toEqual(false);214 model.addbefore = false;215 model.addafter = true;216 expect(model.hasAddons()).toEqual(true);217 });218 });219 describe('hasChanged method', function () {220 it('check without changes', function () {221 expect(model.hasChanged()).toEqual(false);222 });223 it('check with changed value', function () {224 model.value(1);225 expect(model.hasChanged()).toEqual(true);226 });227 it('check with hidden', function () {228 model.visible(false);229 expect(model.hasChanged()).toEqual(false);230 });231 it('check with hidden and changed value', function () {232 model.visible(false);233 model.value(1);234 expect(model.hasChanged()).toEqual(false);235 });236 });237 describe('hasData method', function () {238 it('check with empty value', function () {239 expect(model.hasData()).toEqual(false);240 });241 it('check with value', function () {242 model.value(1);243 expect(model.hasData()).toEqual(true);244 });245 });246 describe('reset method', function () {247 it('check with default value', function () {248 model.reset();249 expect(model.value()).toEqual(model.initialValue);250 });251 it('check with changed value', function () {252 model.value(1);253 model.reset();254 expect(model.value()).toEqual(model.initialValue);255 });256 });257 describe('clear method', function () {258 it('check with default value', function () {259 expect(model.clear()).toEqual(model);260 expect(model.value()).toEqual('');261 });262 it('check with changed value', function () {263 model.value(1);264 expect(model.clear()).toEqual(model);265 expect(model.value()).toEqual('');266 });267 });268 describe('validate method', function () {269 it('check with default value', function () {270 var expected = {271 valid: false,272 target: model273 };274 model.validation = 'validate-no-empty';275 expect(model.validate()).toEqual(expected);276 });277 it('check with valid value', function () {278 var expected = {279 valid: true,280 target: model281 };282 model.validation = 'validate-no-empty';283 model.value('valid');284 expect(model.validate()).toEqual(expected);285 });286 it('check if element hidden and value not valid', function () {287 var expected = {288 valid: true,289 target: model290 };291 model.validation = 'validate-no-empty';292 model.visible(false);293 expect(model.validate()).toEqual(expected);294 });295 it('check if element hidden and value valid', function () {296 var expected = {297 valid: true,298 target: model299 };300 model.validation = 'validate-no-empty';301 model.visible(false);302 model.value('valid');303 expect(model.validate()).toEqual(expected);304 });305 });306 describe('onUpdate method', function () {307 it('check for method call', function () {308 spyOn(model, 'bubble');309 spyOn(model, 'hasChanged');310 spyOn(model, 'validate');311 model.onUpdate();312 expect(model.bubble).toHaveBeenCalled();313 expect(model.hasChanged).toHaveBeenCalled();314 expect(model.validate).toHaveBeenCalled();315 });316 });317 describe('serviceDisabled property', function () {318 it('check property state', function () {319 expect(typeof model.serviceDisabled).toEqual('function');320 expect(model.serviceDisabled()).toBeFalsy();321 });322 });323 });...

Full Screen

Full Screen

rulesEngineModel.js

Source:rulesEngineModel.js Github

copy

Full Screen

1/*****2 License3 --------------4 Copyright © 2017 Bill & Melinda Gates Foundation5 The Mojaloop files are made available by the Bill & Melinda Gates Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at6 http://www.apache.org/licenses/LICENSE-2.07 Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.8 Contributors9 --------------10 This is the official list of the Mojaloop project contributors for this file.11 Names of the original copyright holders (individuals or organizations)12 should be listed with a '*' in the first column. People who have13 contributed from an organization can be listed under the organization14 that actually holds the copyright for their contributions (see the15 Gates Foundation organization for an example). Those individuals should have16 their names indented and be marked with a '-'. Email address can be added17 optionally within square brackets <email>.18 * Gates Foundation19 * ModusBox20 * Georgi Logodazhki <georgi.logodazhki@modusbox.com>21 * Vijaya Kumar Guthi <vijaya.guthi@modusbox.com> (Original Author)22 --------------23 ******/24const RulesEngine = require('./rulesEngine')25const customLogger = require('./requestLogger')26const Config = require('./config')27const storageAdapter = require('./storageAdapter')28const DEFAULT_RULES_FILE_NAME = 'default.json'29const CONFIG_FILE_NAME = 'config.json'30const model = {31 data: {32 response: {33 rulesFilePathPrefix: 'spec_files/rules_response/',34 rules: null,35 rulesEngine: null,36 activeRulesFile: DEFAULT_RULES_FILE_NAME,37 ruleType: 'response'38 },39 validation: {40 rulesFilePathPrefix: 'spec_files/rules_validation/',41 rules: null,42 rulesEngine: null,43 activeRulesFile: DEFAULT_RULES_FILE_NAME,44 ruleType: 'validation'45 },46 callback: {47 rulesFilePathPrefix: 'spec_files/rules_callback/',48 rules: null,49 rulesEngine: null,50 activeRulesFile: DEFAULT_RULES_FILE_NAME,51 ruleType: 'callback'52 },53 forward: {54 rulesFilePathPrefix: 'spec_files/rules_forward/',55 rules: null,56 rulesEngine: null,57 activeRulesFile: DEFAULT_RULES_FILE_NAME,58 ruleType: 'forward'59 }60 }61}62const getModel = async (user, dfspType) => {63 if (user) {64 const dfspId = user.dfspId65 if (!model[dfspId]) {66 model[dfspId] = {}67 }68 if (!model[dfspId][dfspType]) {69 model[dfspId][dfspType] = { ...model.data[dfspType] }70 await getRulesFiles(model[dfspId][dfspType], user)71 }72 return model[dfspId][dfspType]73 }74 return model.data[dfspType]75}76// response rules77const reloadResponseRules = async (user) => {78 const model = await getModel(user, 'response')79 await reloadRules(model, user)80}81const setActiveResponseRulesFile = async (fileName, user) => {82 const model = await getModel(user, 'response')83 await setActiveRulesFile(model, fileName, user)84}85const getResponseRules = async (user) => {86 const model = await getModel(user, 'response')87 const rules = await getRules(model, user)88 return rules89}90const getResponseRulesEngine = async (convertedRules, user) => {91 const model = await getModel(user, 'response')92 const rulesEngine = await getRulesEngine(model, convertedRules, user)93 return rulesEngine94}95const getResponseRulesFiles = async (user) => {96 // await getResponseRules(user)97 const model = await getModel(user, 'response')98 const rulesFiles = await getRulesFiles(model, user)99 return rulesFiles100}101const getResponseRulesFileContent = async (fileName, user) => {102 const model = await getModel(user, 'response')103 const rulesFileContent = await getRulesFileContent(model, fileName, user)104 return rulesFileContent105}106const setResponseRulesFileContent = async (fileName, fileContent, user) => {107 const model = await getModel(user, 'response')108 const rulesFileContent = await setRulesFileContent(model, fileName, fileContent, user)109 return rulesFileContent110}111const deleteResponseRulesFile = async (fileName, user) => {112 const model = await getModel(user, 'response')113 const deleted = await deleteRulesFile(model, fileName, user)114 return deleted115}116// validation rules117const reloadValidationRules = async (user) => {118 const model = await getModel(user, 'validation')119 await reloadRules(model, user)120}121const setActiveValidationRulesFile = async (fileName, user) => {122 const model = await getModel(user, 'validation')123 await setActiveRulesFile(model, fileName, user)124}125const getValidationRules = async (user) => {126 const model = await getModel(user, 'validation')127 const rules = await getRules(model, user)128 return rules129}130const getValidationRulesEngine = async (convertedRules, user) => {131 const model = await getModel(user, 'validation')132 const rulesEngine = await getRulesEngine(model, convertedRules, user)133 return rulesEngine134}135const getValidationRulesFiles = async (user) => {136 // await getValidationRules(user)137 const model = await getModel(user, 'validation')138 const rulesFiles = await getRulesFiles(model, user)139 return rulesFiles140}141const getValidationRulesFileContent = async (fileName, user) => {142 const model = await getModel(user, 'validation')143 const rulesFileContent = await getRulesFileContent(model, fileName, user)144 return rulesFileContent145}146const setValidationRulesFileContent = async (fileName, fileContent, user) => {147 const model = await getModel(user, 'validation')148 const rulesFileContent = await setRulesFileContent(model, fileName, fileContent, user)149 return rulesFileContent150}151const deleteValidationRulesFile = async (fileName, user) => {152 const model = await getModel(user, 'validation')153 const deleted = await deleteRulesFile(model, fileName, user)154 return deleted155}156// callback rules157const reloadCallbackRules = async (user) => {158 const model = await getModel(user, 'callback')159 await reloadRules(model, user)160}161const setActiveCallbackRulesFile = async (fileName, user) => {162 const model = await getModel(user, 'callback')163 await setActiveRulesFile(model, fileName, user)164}165const getCallbackRules = async (user) => {166 const model = await getModel(user, 'callback')167 const rules = await getRules(model, user)168 return rules169}170const getCallbackRulesEngine = async (convertedRules, user) => {171 const model = await getModel(user, 'callback')172 const rulesEngine = await getRulesEngine(model, convertedRules, user)173 return rulesEngine174}175const getCallbackRulesFiles = async (user) => {176 // await getCallbackRules(user)177 const model = await getModel(user, 'callback')178 const rulesFiles = await getRulesFiles(model, user)179 return rulesFiles180}181const getCallbackRulesFileContent = async (fileName, user) => {182 const model = await getModel(user, 'callback')183 const rulesFileContent = await getRulesFileContent(model, fileName, user)184 return rulesFileContent185}186const setCallbackRulesFileContent = async (fileName, fileContent, user) => {187 const model = await getModel(user, 'callback')188 const rulesFileContent = await setRulesFileContent(model, fileName, fileContent, user)189 return rulesFileContent190}191const deleteCallbackRulesFile = async (fileName, user) => {192 const model = await getModel(user, 'callback')193 const deleted = await deleteRulesFile(model, fileName, user)194 return deleted195}196// forward rules197const reloadForwardRules = async (user) => {198 const model = await getModel(user, 'forward')199 await reloadRules(model, user)200}201const setActiveForwardRulesFile = async (fileName, user) => {202 const model = await getModel(user, 'forward')203 await setActiveRulesFile(model, fileName, user)204}205const getForwardRules = async (user) => {206 const model = await getModel(user, 'forward')207 const rules = await getRules(model, user)208 return rules209}210const getForwardRulesEngine = async (convertedRules, user) => {211 const model = await getModel(user, 'forward')212 const rulesEngine = await getRulesEngine(model, convertedRules, user)213 return rulesEngine214}215const getForwardRulesFiles = async (user) => {216 // await getForwardRules(user)217 const model = await getModel(user, 'forward')218 const rulesFiles = await getRulesFiles(model, user)219 return rulesFiles220}221const getForwardRulesFileContent = async (fileName, user) => {222 const model = await getModel(user, 'forward')223 const rulesFileContent = await getRulesFileContent(model, fileName, user)224 return rulesFileContent225}226const setForwardRulesFileContent = async (fileName, fileContent, user) => {227 const model = await getModel(user, 'forward')228 const rulesFileContent = await setRulesFileContent(model, fileName, fileContent, user)229 return rulesFileContent230}231const deleteForwardRulesFile = async (fileName, user) => {232 const model = await getModel(user, 'forward')233 const deleted = await deleteRulesFile(model, fileName, user)234 return deleted235}236// common functions237const reloadRules = async (model, user) => {238 const fetchedActiveRulesFile = await getActiveRulesFile(model, user)239 if (fetchedActiveRulesFile) {240 model.activeRulesFile = fetchedActiveRulesFile241 }242 customLogger.logMessage('info', `Reloading ${model.ruleType} Rules from file ` + model.activeRulesFile, { notification: false })243 const userRules = await storageAdapter.read(model.rulesFilePathPrefix + model.activeRulesFile, user)244 model.rules = userRules.data245 if (!model.rules || !model.rules.length) {246 model.rules = []247 }248 loadRules(model, model.rules)249}250const setActiveRulesFile = async (model, fileName, user) => {251 const rulesConfig = {252 activeRulesFile: fileName253 }254 await storageAdapter.upsert(model.rulesFilePathPrefix + CONFIG_FILE_NAME, rulesConfig, user)255 model.activeRulesFile = fileName256 await reloadRules(model, user)257}258const getActiveRulesFile = async (model, user) => {259 const configFileContent = await storageAdapter.read(model.rulesFilePathPrefix + CONFIG_FILE_NAME, user)260 return configFileContent.data.activeRulesFile261}262const getRules = async (model, user) => {263 if (!model.rules || model.rules.length === 0) {264 await reloadRules(model, user)265 }266 return model.rules267}268const getRulesEngine = async (model, convertedRules) => {269 if (!model.rulesEngine) {270 model.rulesEngine = new RulesEngine()271 }272 if (convertedRules) {273 loadRules(model, convertedRules)274 }275 return model.rulesEngine276}277const loadRules = (model, rules) => {278 rules.forEach(rule => {279 rule.conditions.all.forEach(condition => {280 if (condition.fact === 'headers') {281 condition.path = condition.path.toLowerCase()282 }283 })284 })285 if (!model.rulesEngine) {286 model.rulesEngine = new RulesEngine()287 }288 model.rulesEngine.loadRules(rules)289}290const getRulesFiles = async (model, user) => {291 try {292 const files = await storageAdapter.read(model.rulesFilePathPrefix, user)293 const resp = {}294 // Do not return the config file295 resp.files = files.data.filter(item => {296 return (item !== CONFIG_FILE_NAME)297 })298 if (model.rules === null) {299 await reloadRules(model, user)300 }301 resp.activeRulesFile = model.activeRulesFile302 return resp303 } catch (err) {304 return null305 }306}307const deleteRulesFile = async (model, fileName, user) => {308 try {309 await storageAdapter.remove(model.rulesFilePathPrefix + fileName, user)310 await setActiveRulesFile(model, DEFAULT_RULES_FILE_NAME, user)311 return true312 } catch (err) {313 return err314 }315}316const setRulesFileContent = async (model, fileName, fileContent, user) => {317 try {318 addTypeAndVersion(model, fileContent)319 await storageAdapter.upsert(model.rulesFilePathPrefix + fileName, fileContent, user)320 await reloadRules(model, user)321 return true322 } catch (err) {323 return err324 }325}326const getRulesFileContent = async (model, fileName, user) => {327 const userRules = await storageAdapter.read(model.rulesFilePathPrefix + fileName, user)328 return userRules.data329}330const addTypeAndVersion = (model, fileContent) => {331 for (const index in fileContent) {332 if (!fileContent[index].type) {333 fileContent[index].type = model.ruleType334 }335 if (!fileContent[index].version) {336 fileContent[index].version = parseFloat(Config.getSystemConfig().CONFIG_VERSIONS[model.ruleType])337 }338 }339}340module.exports = {341 getModel,342 reloadResponseRules,343 setActiveResponseRulesFile,344 getResponseRules,345 getResponseRulesEngine,346 getResponseRulesFiles,347 getResponseRulesFileContent,348 setResponseRulesFileContent,349 deleteResponseRulesFile,350 reloadValidationRules,351 setActiveValidationRulesFile,352 getValidationRules,353 getValidationRulesEngine,354 getValidationRulesFiles,355 getValidationRulesFileContent,356 setValidationRulesFileContent,357 deleteValidationRulesFile,358 reloadCallbackRules,359 setActiveCallbackRulesFile,360 getCallbackRules,361 getCallbackRulesEngine,362 getCallbackRulesFiles,363 getCallbackRulesFileContent,364 setCallbackRulesFileContent,365 deleteCallbackRulesFile,366 reloadForwardRules,367 setActiveForwardRulesFile,368 getForwardRules,369 getForwardRulesEngine,370 getForwardRulesFiles,371 getForwardRulesFileContent,372 setForwardRulesFileContent,373 deleteForwardRulesFile...

Full Screen

Full Screen

Cesium3DTilesInspectorViewModelSpec.js

Source:Cesium3DTilesInspectorViewModelSpec.js Github

copy

Full Screen

1defineSuite([2 'Widgets/Cesium3DTilesInspector/Cesium3DTilesInspectorViewModel',3 'Core/defined',4 'Core/Math',5 'Scene/Cesium3DTileset',6 'Scene/Cesium3DTileStyle',7 'Scene/Globe',8 'Specs/createScene',9 'ThirdParty/when'10 ], function(11 Cesium3DTilesInspectorViewModel,12 defined,13 CesiumMath,14 Cesium3DTileset,15 Cesium3DTileStyle,16 Globe,17 createScene,18 when) {19 'use strict';2021 // Parent tile with content and four child tiles with content22 var tilesetUrl = './Data/Cesium3DTiles/Tilesets/Tileset/';2324 var scene;25 var viewModel;26 var performanceContainer = document.createElement('div');2728 beforeAll(function() {29 scene = createScene();30 });3132 afterAll(function() {33 scene.destroyForSpecs();34 });3536 beforeEach(function() {37 scene.globe = new Globe();38 scene.initializeFrame();39 });4041 afterEach(function() {42 scene.primitives.removeAll();43 });4445 it('can create and destroy', function() {46 var viewModel = new Cesium3DTilesInspectorViewModel(scene, performanceContainer);47 expect(viewModel._scene).toBe(scene);48 expect(viewModel.isDestroyed()).toEqual(false);49 viewModel.destroy();50 expect(viewModel.isDestroyed()).toEqual(true);51 });5253 it('throws if scene is undefined', function() {54 expect(function() {55 return new Cesium3DTilesInspectorViewModel();56 }).toThrowDeveloperError();57 });5859 it('throws if performanceContainer is undefined', function() {60 expect(function() {61 return new Cesium3DTilesInspectorViewModel(scene);62 }).toThrowDeveloperError();63 });6465 describe('tileset options', function() {66 it('show properties', function() {67 viewModel = new Cesium3DTilesInspectorViewModel(scene, performanceContainer);68 var tileset = new Cesium3DTileset({69 url : tilesetUrl70 });71 viewModel.tileset = tileset;72 var done = when.defer();73 tileset.readyPromise.then(function() {74 expect(viewModel.properties.indexOf('id') !== -1).toBe(true);75 expect(viewModel.properties.indexOf('Longitude') !== -1).toBe(true);76 expect(viewModel.properties.indexOf('Latitude') !== -1).toBe(true);77 expect(viewModel.properties.indexOf('Height') !== -1).toBe(true);78 viewModel.destroy();79 done.resolve();80 });81 return done;82 });83 });8485 describe('display options', function() {86 beforeAll(function() {87 viewModel = new Cesium3DTilesInspectorViewModel(scene, performanceContainer);88 var tileset = new Cesium3DTileset({89 url : tilesetUrl90 });91 viewModel.tileset = tileset;92 return tileset.readyPromise;93 });9495 afterAll(function() {96 viewModel.destroy();97 });9899 it('colorize', function() {100 viewModel.colorize = true;101 expect(viewModel.tileset.debugColorizeTiles).toBe(true);102 viewModel.colorize = false;103 expect(viewModel.tileset.debugColorizeTiles).toBe(false);104 });105106 it('wireframe', function() {107 viewModel.wireframe = true;108 expect(viewModel.tileset.debugWireframe).toBe(true);109 viewModel.wireframe = false;110 expect(viewModel.tileset.debugWireframe).toBe(false);111 });112113 it('showBoundingVolumes', function() {114 viewModel.showBoundingVolumes = true;115 expect(viewModel.tileset.debugShowBoundingVolume).toBe(true);116 viewModel.showBoundingVolumes = false;117 expect(viewModel.tileset.debugShowBoundingVolume).toBe(false);118 });119120 it('showContentVolumes', function() {121 viewModel.showContentBoundingVolumes = true;122 expect(viewModel.tileset.debugShowContentBoundingVolume).toBe(true);123 viewModel.showContentBoundingVolumes = false;124 expect(viewModel.tileset.debugShowContentBoundingVolume).toBe(false);125 });126127 it('showRequestVolumes', function() {128 viewModel.showRequestVolumes = true;129 expect(viewModel.tileset.debugShowViewerRequestVolume).toBe(true);130 viewModel.showRequestVolumes = false;131 expect(viewModel.tileset.debugShowViewerRequestVolume).toBe(false);132 });133134 it('showOnlyPickedTileDebugLabel', function() {135 viewModel.showOnlyPickedTileDebugLabel = true;136 expect(viewModel.tileset.debugPickedTileLabelOnly).toBe(true);137 viewModel.showOnlyPickedTileDebugLabel = false;138 expect(viewModel.tileset.debugPickedTileLabelOnly).toBe(false);139 });140141 it('showGeometricError', function() {142 viewModel.showGeometricError = true;143 expect(viewModel.tileset.debugShowGeometricError).toBe(true);144 viewModel.showGeometricError = false;145 expect(viewModel.tileset.debugShowGeometricError).toBe(false);146 });147148 it('showRenderingStatistics', function() {149 viewModel.showRenderingStatistics = true;150 expect(viewModel.tileset.debugShowRenderingStatistics).toBe(true);151 viewModel.showRenderingStatistics = false;152 expect(viewModel.tileset.debugShowRenderingStatistics).toBe(false);153 });154155 it('showMemoryUsage', function() {156 viewModel.showMemoryUsage = true;157 expect(viewModel.tileset.debugShowMemoryUsage).toBe(true);158 viewModel.showMemoryUsage = false;159 expect(viewModel.tileset.debugShowMemoryUsage).toBe(false);160 });161162 it('showUrl', function() {163 viewModel.showUrl = true;164 expect(viewModel.tileset.debugShowUrl).toBe(true);165 viewModel.showUrl = false;166 expect(viewModel.tileset.debugShowUrl).toBe(false);167 });168 });169170 describe('update options', function() {171 beforeAll(function() {172 viewModel = new Cesium3DTilesInspectorViewModel(scene, performanceContainer);173 viewModel.tileset = new Cesium3DTileset({174 url : tilesetUrl175 });176 return viewModel.tileset.readyPromise;177 });178179 afterAll(function() {180 viewModel.destroy();181 });182183 it('freeze frame', function() {184 viewModel.freezeFrame = false;185 expect(viewModel.tileset.debugFreezeFrame).toBe(false);186 viewModel.freezeFrame = true;187 expect(viewModel.tileset.debugFreezeFrame).toBe(true);188 });189190 it('maximum screen space error', function() {191 viewModel.dynamicScreenSpaceError = false;192 viewModel.maximumScreenSpaceError = 10;193 expect(viewModel.tileset.dynamicScreenSpaceError).toBe(false);194 expect(viewModel.tileset.maximumScreenSpaceError).toBe(10);195 });196197 it('dynamic screen space error', function() {198 viewModel.dynamicScreenSpaceError = true;199 viewModel.dynamicScreenSpaceErrorFactor = 2;200 viewModel.dynamicScreenSpaceErrorDensity = 0.1;201 expect(viewModel.tileset.dynamicScreenSpaceError).toBe(true);202 expect(viewModel.tileset.dynamicScreenSpaceErrorFactor).toBe(2);203 expect(viewModel.tileset.dynamicScreenSpaceErrorDensity).toBe(0.1);204 });205 });206207 describe('style options', function() {208 var style;209210 beforeAll(function() {211 style = new Cesium3DTileStyle({212 color : {213 conditions : [214 ["${Height} >= 83", "color('purple', 0.5)"],215 ["${Height} >= 80", "color('red')"],216 ["${Height} >= 70", "color('orange')"],217 ["${Height} >= 12", "color('yellow')"],218 ["${Height} >= 7", "color('lime')"],219 ["${Height} >= 1", "color('cyan')"],220 ["true", "color('blue')"]221 ]222 },223 meta : {224 description : "'Building id ${id} has height ${Height}.'"225 }226 });227228 viewModel = new Cesium3DTilesInspectorViewModel(scene, performanceContainer);229 viewModel.tileset = new Cesium3DTileset({230 url : tilesetUrl231 });232233 return viewModel.tileset.readyPromise;234 });235236 afterAll(function() {237 viewModel.destroy();238 });239240 it('loads tileset style', function() {241 viewModel.tileset.style = style;242 viewModel._update();243 expect(JSON.stringify(style.style)).toBe(JSON.stringify(JSON.parse(viewModel.styleString)));244 });245246 it('does not throw on invalid syntax', function() {247 expect(function() {248 viewModel.styleString = 'invalid';249 }).not.toThrowError();250 });251252 it('recompiles style', function() {253 viewModel._style = undefined;254 viewModel.tileset.style = style;255 viewModel._update();256 var s = JSON.parse(viewModel.styleString);257 s.color = "color('red')";258 viewModel.styleString = JSON.stringify(s);259 viewModel.compileStyle();260 viewModel._update();261 expect(viewModel.tileset.style.style.color).toBe("color('red')");262 expect(viewModel.tileset.style.style.meta.description).toBe("'Building id ${id} has height ${Height}.'");263 });264265 it('does not throw on invalid value', function() {266 expect(function() {267 viewModel.styleString = '{ "color": "color(1)" }';268 }).not.toThrowError();269 });270 }); ...

Full Screen

Full Screen

select.test.js

Source:select.test.js Github

copy

Full Screen

1/**2 * Copyright © Magento, Inc. All rights reserved.3 * See COPYING.txt for license details.4 */5/*eslint max-nested-callbacks: 0*/6define([7 'squire'8], function (Squire) {9 'use strict';10 describe('Magento_Ui/js/form/element/select', function () {11 var injector = new Squire(),12 mocks = {13 'Magento_Ui/js/lib/registry/registry': {14 /** Method stub. */15 get: function () {16 return {17 get: jasmine.createSpy(),18 set: jasmine.createSpy()19 };20 },21 options: jasmine.createSpy(),22 create: jasmine.createSpy(),23 set: jasmine.createSpy(),24 async: jasmine.createSpy()25 },26 '/mage/utils/wrapper': jasmine.createSpy(),27 'Magento_Ui/js/core/renderer/layout': jasmine.createSpy()28 },29 dataScope = 'select',30 params = {31 provider: 'provName',32 name: '',33 index: '',34 dataScope: dataScope35 },36 model;37 beforeEach(function (done) {38 injector.mock(mocks);39 injector.require([40 'Magento_Ui/js/form/element/select',41 'knockoutjs/knockout-es5',42 'Magento_Ui/js/lib/knockout/extender/observable_array'43 ], function (Constr) {44 model = new Constr(params);45 done();46 });47 });48 describe('initialize method', function () {49 it('check for existing', function () {50 expect(model).toBeDefined();51 });52 it('check for chainable', function () {53 spyOn(model, 'initFilter');54 expect(model.initialize(params)).toEqual(model);55 expect(model.initFilter).not.toHaveBeenCalled();56 });57 it('check for call initInput', function () {58 spyOn(model, 'initFilter');59 model.customEntry = true;60 expect(model.initialize(params)).toEqual(model);61 expect(model.initFilter).not.toHaveBeenCalled();62 });63 it('check for call initFilter', function () {64 spyOn(model, 'initFilter');65 model.filterBy = true;66 expect(model.initialize(params)).toEqual(model);67 expect(model.initFilter).toHaveBeenCalled();68 });69 });70 describe('initConfig method', function () {71 it('check for chainable', function () {72 expect(model.initConfig({})).toEqual(model);73 });74 });75 describe('initObservable method', function () {76 it('check for chainable', function () {77 expect(model.initObservable({})).toEqual(model);78 });79 it('check for options', function () {80 spyOn(model, 'setOptions');81 expect(model.initObservable({})).toEqual(model);82 expect(model.setOptions).toHaveBeenCalled();83 expect(model.options()).toEqual([]);84 });85 });86 describe('initFilter method', function () {87 it('check for filter', function () {88 spyOn(model, 'filter');89 spyOn(model, 'setLinks');90 model.filterBy = {91 field: true92 };93 expect(model.initFilter()).toEqual(model);94 expect(model.filter).toHaveBeenCalled();95 expect(model.setLinks).toHaveBeenCalled();96 });97 });98 describe('initInput method', function () {99 it('check for chainable', function () {100 expect(model.initInput()).toEqual(model);101 });102 });103 describe('getOption method', function () {104 it('check existed option', function () {105 model.indexedOptions = {106 value: 'option'107 };108 expect(model.getOption('value')).toEqual('option');109 });110 it('check not existed option', function () {111 expect(model.getOption('value')).not.toBeDefined();112 });113 it('check empty value', function () {114 model.indexedOptions = {115 value: 'option'116 };117 expect(model.getOption('')).not.toBeDefined();118 });119 });120 describe('normalizeData method', function () {121 it('check on non empty value', function () {122 spyOn(model, 'getOption').and.callThrough();123 model.indexedOptions = {124 val: {125 value: 'value'126 }127 };128 expect(model.normalizeData('val')).toEqual('value');129 expect(model.getOption).toHaveBeenCalledWith('val');130 });131 it('check on not existed option value', function () {132 expect(model.normalizeData('value')).not.toBeDefined();133 });134 it('check on empty value', function () {135 model.options = [{136 value: 'valFirst'137 },138 {139 value: 'valLast'140 }];141 model.caption('');142 expect(model.normalizeData('')).toEqual('valFirst');143 });144 });145 describe('getInitialValue method', function () {146 it('check on non empty value', function () {147 model.value('val');148 model.indexedOptions = {149 val: {150 value: 'value'151 }152 };153 spyOn(model, 'normalizeData').and.callThrough();154 expect(model.getInitialValue()).toEqual('value');155 expect(model.normalizeData).toHaveBeenCalledWith('val');156 });157 it('check on empty value', function () {158 model.options = [{159 label: 'Label',160 value: 'Value'161 }];162 expect(model.getInitialValue()).toEqual('Value');163 });164 });165 describe('filter method', function () {166 it('check for filter', function () {167 spyOn(model, 'setOptions');168 model.filter('Value', 'Name');169 expect(model.setOptions).toHaveBeenCalled();170 });171 });172 describe('toggleInput method', function () {173 it('check for toggling', function () {174 expect(model.toggleInput()).toEqual(undefined);175 });176 });177 describe('setOptions method', function () {178 it('check for chainable', function () {179 expect(model.setOptions([])).toEqual(model);180 });181 it('check for default customEntry', function () {182 var data = [{183 value: 'First'184 }, {185 value: 'Second'186 }];187 spyOn(model, 'setVisible');188 spyOn(model, 'toggleInput');189 expect(model.setOptions(data)).toEqual(model);190 expect(model.setVisible).not.toHaveBeenCalled();191 expect(model.toggleInput).not.toHaveBeenCalled();192 });193 it('check for customEntry', function () {194 var data = [{195 value: 'First'196 }, {197 value: 'Second'198 }];199 model.customEntry = true;200 spyOn(model, 'setVisible');201 spyOn(model, 'toggleInput');202 expect(model.setOptions(data)).toEqual(model);203 expect(model.setVisible).toHaveBeenCalled();204 expect(model.toggleInput).toHaveBeenCalled();205 });206 it('Check call "parseOptions" method without predefined "captionValue" property', function () {207 var data = [{208 value: null,209 label: 'label'210 }, {211 value: 'value'212 }];213 model.options = jasmine.createSpy();214 model.caption = jasmine.createSpy().and.returnValue(false);215 model.setOptions(data);216 expect(model.options).toHaveBeenCalledWith([{217 value: 'value'218 }]);219 expect(model.caption.calls.allArgs()).toEqual([[], ['label']]);220 });221 it('Check call "parseOptions" method with predefined "captionValue" property', function () {222 var data = [{223 value: 'value',224 label: 'label'225 }];226 model.options = jasmine.createSpy();227 model.caption = jasmine.createSpy().and.returnValue(false);228 model.captionValue = 'value';229 model.setOptions(data);230 expect(model.options).toHaveBeenCalledWith([]);231 expect(model.caption.calls.allArgs()).toEqual([[], ['label']]);232 });233 });234 describe('getPreview method', function () {235 it('check for default preview', function () {236 expect(model.getPreview()).toEqual('');237 });238 it('check with options', function () {239 var expected = {240 value: 'some',241 label: 'Label'242 };243 model.indexedOptions = {244 some: expected245 };246 model.value(expected.value);247 expect(model.getPreview()).toEqual(expected.label);248 expect(model.preview()).toEqual(expected.label);249 });250 });251 });...

Full Screen

Full Screen

DAO.js

Source:DAO.js Github

copy

Full Screen

1var path = require("path");2// 获取数据库模型3databaseModule = require(path.join(process.cwd(),"modules/database")); 4var logger = require('../modules/logger').logger();5/**6 * 创建对象数据7 * 8 * @param {[type]} modelName 模型名称9 * @param {[type]} obj 模型对象10 * @param {Function} cb 回调函数11 */12module.exports.create = function(modelName,obj,cb) {13 var db = databaseModule.getDatabase();14 var Model = db.models[modelName];15 Model.create(obj,cb);16}17/**18 * 获取所有数据19 * 20 * @param {[type]} conditions 查询条件21 * 查询条件统一规范22 * conditions23 {24 "columns" : {25 字段条件26 "字段名" : "条件值"27 },28 "offset" : "偏移",29 "omit" : ["字段"],30 "only" : ["需要字段"],31 "limit" : "",32 "order" :[ 33 "字段" , A | Z,34 ...35 ]36 }37 * @param {Function} cb 回调函数38 */39module.exports.list = function(modelName,conditions,cb) {40 var db = databaseModule.getDatabase();41 var model = db.models[modelName];42 if(!model) return cb("模型不存在",null);43 if(conditions) {44 if(conditions["columns"]) {45 model = model.find(conditions["columns"]);46 } else {47 model = model.find();48 }49 if(conditions["offset"]) {50 model = model.offset(parseInt(conditions["offset"]));51 }52 if(conditions["limit"]) {53 model = model.limit(parseInt(conditions["limit"]));54 }55 if(conditions["only"]) {56 model = model.only(conditions["only"]);57 }58 if(conditions["omit"]) {59 model = model.omit(conditions["omit"]);60 }61 if(conditions["order"]) {62 model = model.order(conditions["order"]);63 }64 } else {65 model = model.find();66 }67 model.run(function(err,models) {68 69 if(err) {70 console.log(err);71 return cb("查询失败",null);72 }73 cb(null,models);74 });75};76module.exports.countByConditions = function(modelName,conditions,cb) {77 var db = databaseModule.getDatabase();78 var model = db.models[modelName];79 if(!model) return cb("模型不存在",null);80 var resultCB = function(err,count){81 if(err) {82 return cb("查询失败",null);83 }84 cb(null,count);85 }86 if(conditions) {87 if(conditions["columns"]) {88 model = model.count(conditions["columns"],resultCB);89 } else {90 model = model.count(resultCB);91 }92 } else {93 model = model.count(resultCB);94 }95};96/**97 * 获取一条数据98 * @param {[type]} modelName 模型名称99 * @param {[数组]} conditions 条件集合100 * @param {Function} cb 回调函数101 */102module.exports.findOne = function(modelName,conditions,cb) {103 var db = databaseModule.getDatabase();104 var Model = db.models[modelName];105 if(!Model) return cb("模型不存在",null);106 if(!conditions) return cb("条件为空",null);107 Model.one(conditions,function(err,obj){108 logger.debug(err);109 if(err) {110 return cb("查询失败",null);111 }112 return cb(null,obj);113 });114}115/**116 * 更新对象数据117 * 118 * @param {[type]} modelName 模型名称119 * @param {[type]} id 数据关键ID120 * @param {[type]} updateObj 更新对象数据121 * @param {Function} cb 回调函数122 */123module.exports.update = function(modelName,id,updateObj,cb) {124 var db = databaseModule.getDatabase();125 var Model = db.models[modelName];126 Model.get(id,function(err,obj){127 if(err) return cb("更新失败",null);128 obj.save(updateObj,cb);129 });130}131/**132 * 通过主键ID获取对象133 * @param {[type]} modelName 模型名称134 * @param {[type]} id 主键ID135 * @param {Function} cb 回调函数136 */137module.exports.show = function(modelName,id,cb) {138 var db = databaseModule.getDatabase();139 var Model = db.models[modelName];140 Model.get(id,function(err,obj){141 cb(err,obj);142 });143}144/**145 * 通过主键ID删除对象146 * 147 * @param {[type]} modelName 模型名称148 * @param {[type]} id 主键ID149 * @param {Function} cb 回调函数150 */151module.exports.destroy = function(modelName,id,cb) {152 var db = databaseModule.getDatabase();153 var Model = db.models[modelName];154 Model.get(id,function(err,obj){155 if(err) return cb("无模型ID");156 obj.remove(function(err) {157 if(err) return cb("删除失败");158 return cb(null);159 });160 });161}162/**163 * 通过模型名称获取数据库数量164 * 165 * @param {[type]} modelName 模型名称166 * @param {Function} cb 回调函数167 */168module.exports.count = function(modelName,cb) {169 var db = databaseModule.getDatabase();170 var Model = db.models[modelName];171 Model.count(cb);172}173/**174 * 通过条件判断数据是否存在175 * 176 * @param {[type]} modelName 模块名177 * @param {[type]} conditions 条件178 * @param {Function} cb 回调函数179 */180module.exports.exists = function(modelName,conditions,cb) {181 var db = databaseModule.getDatabase();182 var Model = db.models[modelName];183 Model.exists(conditions,function(err,isExists){184 if(err) return cb("查询失败");185 cb(null,isExists);186 });187}188module.exports.getModel = function(modelName) {189 var db = databaseModule.getDatabase();190 return db.models[modelName];...

Full Screen

Full Screen

Model.js

Source:Model.js Github

copy

Full Screen

1/**2 * @module echarts/model/Model3 */4define(function (require) {5 var zrUtil = require('zrender/core/util');6 var clazzUtil = require('../util/clazz');7 /**8 * @alias module:echarts/model/Model9 * @constructor10 * @param {Object} option11 * @param {module:echarts/model/Model} [parentModel]12 * @param {module:echarts/model/Global} [ecModel]13 * @param {Object} extraOpt14 */15 function Model(option, parentModel, ecModel, extraOpt) {16 /**17 * @type {module:echarts/model/Model}18 * @readOnly19 */20 this.parentModel = parentModel;21 /**22 * @type {module:echarts/model/Global}23 * @readOnly24 */25 this.ecModel = ecModel;26 /**27 * @type {Object}28 * @protected29 */30 this.option = option;31 // Simple optimization32 if (this.init) {33 if (arguments.length <= 4) {34 this.init(option, parentModel, ecModel, extraOpt);35 }36 else {37 this.init.apply(this, arguments);38 }39 }40 }41 Model.prototype = {42 constructor: Model,43 /**44 * Model 的初始化函数45 * @param {Object} option46 */47 init: null,48 /**49 * 从新的 Option merge50 */51 mergeOption: function (option) {52 zrUtil.merge(this.option, option, true);53 },54 /**55 * @param {string} path56 * @param {boolean} [ignoreParent=false]57 * @return {*}58 */59 get: function (path, ignoreParent) {60 if (!path) {61 return this.option;62 }63 if (typeof path === 'string') {64 path = path.split('.');65 }66 var obj = this.option;67 var parentModel = this.parentModel;68 for (var i = 0; i < path.length; i++) {69 // Ignore empty70 if (!path[i]) {71 continue;72 }73 // obj could be number/string/... (like 0)74 obj = (obj && typeof obj === 'object') ? obj[path[i]] : null;75 if (obj == null) {76 break;77 }78 }79 if (obj == null && parentModel && !ignoreParent) {80 obj = parentModel.get(path);81 }82 return obj;83 },84 /**85 * @param {string} key86 * @param {boolean} [ignoreParent=false]87 * @return {*}88 */89 getShallow: function (key, ignoreParent) {90 var option = this.option;91 var val = option && option[key];92 var parentModel = this.parentModel;93 if (val == null && parentModel && !ignoreParent) {94 val = parentModel.getShallow(key);95 }96 return val;97 },98 /**99 * @param {string} path100 * @param {module:echarts/model/Model} [parentModel]101 * @return {module:echarts/model/Model}102 */103 getModel: function (path, parentModel) {104 var obj = this.get(path, true);105 var thisParentModel = this.parentModel;106 var model = new Model(107 obj, parentModel || (thisParentModel && thisParentModel.getModel(path)),108 this.ecModel109 );110 return model;111 },112 /**113 * If model has option114 */115 isEmpty: function () {116 return this.option == null;117 },118 restoreData: function () {},119 // Pending120 clone: function () {121 var Ctor = this.constructor;122 return new Ctor(zrUtil.clone(this.option));123 },124 setReadOnly: function (properties) {125 clazzUtil.setReadOnly(this, properties);126 }127 };128 // Enable Model.extend.129 clazzUtil.enableClassExtend(Model);130 var mixin = zrUtil.mixin;131 mixin(Model, require('./mixin/lineStyle'));132 mixin(Model, require('./mixin/areaStyle'));133 mixin(Model, require('./mixin/textStyle'));134 mixin(Model, require('./mixin/itemStyle'));135 return Model;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright-internal');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'example.png' });15 await browser.close();16})();17"dependencies": {18 }19"scripts": {20 }21const { devices } = require('@playwright/test');22module.exports = {23 use: {24 viewport: { width: 1280, height: 720 },25 }26};27const { test, expect } = require('@playwright/test');28test('basic test', async ({ page }) => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.click('text=Get started');6 await page.waitForTimeout(5000);7 await browser.close();8})();9const {chromium} = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const page = await browser.newPage();13 await page.click('text=Get started');14 await page.waitForTimeout(5000);15 await browser.close();16})();17const {chromium} = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const page = await browser.newPage();21 await page.click('text=Get started');22 await page.waitForTimeout(5000);23 await browser.close();24})();25const {chromium} = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const page = await browser.newPage();29 await page.click('text=Get started');30 await page.waitForTimeout(5000);31 await browser.close();32})();33const {chromium} = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const page = await browser.newPage();37 await page.click('text=Get started');38 await page.waitForTimeout(5000);39 await browser.close();40})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { PlaywrightInternal } = require('@playwright/test');2const { chromium } = PlaywrightInternal;3const browser = await chromium.launch();4const context = await browser.newContext();5const page = await context.newPage();6await page.goto('

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const { Playwright } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const model = await Playwright.createModel(page);8 const button = await model.queryAll('button');9 console.log(button);10 await browser.close();11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { PlaywrightInternal } = require('@playwright/test/lib/server/playwright');2const { Playwright } = require('@playwright/test/lib/server/playwright');3const { BrowserType } = require('@playwright/test/lib/server/browserType');4const { Browser } = require('@playwright/test/lib/server/browser');5const { Page } = require('@playwright/test/lib/server/page');6const { BrowserContext } = require('@playwright/test/lib/server/browserContext');7const { Video } = require('@playwright/test/lib/server/video');8const { Artifact } = require('@playwright/test/lib/server/artifact');9const { Coverage } = require('@playwright/test/lib/server/coverage');10const { Tracing } = require('@playwright/test/lib/server/tracing');11const { ConsoleMessage } = require('@playwright/test/lib/server/consoleMessage');12const { Dialog } = require('@playwright/test/lib/server/dialog');13const { Download } = require('@playwright/test/lib/server/download');14const { Frame } = require('@playwright/test/lib/server/frame');15const { Route } = require('@playwright/test/lib/server/route');16const { Worker } = require('@playwright/test/lib/server/worker');17const { WebSocket } = require('@playwright/test/lib/server/webSocket');18const { Selectors } = require('@playwright/test/lib/server/selectors');19const { WebKit } = require('@playwright/test/lib/server/webKit');20const { WebKitBrowser } = require('@playwright/test/lib/server/webKitBrowser');21const { WebKitBrowserContext } = require('@playwright/test/lib/server/webKitBrowserContext');22const { WebKitPage } = require('@playwright/test/lib/server/webKitPage');23const { WebKitFrame } = require('@playwright/test/lib/server/webKitFrame');24const { WebKitWorker } = require('@playwright/test/lib/server/webKitWorker');25const { WebKitWebSocket } = require('@playwright/test/lib/server/webKitWebSocket');26const { WebKitConsoleMessage } = require('@playwright/test/lib/server/webKitConsoleMessage');27const { WebKitBindingCall } = require('@playwright/test/lib/server/webKitBindingCall');28const { WebKitVideo } = require('@playwright/test/lib/server/webKitVideo');29const { WebKitNetworkRequest } = require('@playwright/test/lib/server/webKitNetworkRequest');30const { WebKitNetworkResponse } = require('@playwright/test/lib/server/webKitNetworkResponse');31const {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Playwright } = require('playwright');2const path = require('path');3const fs = require('fs');4const os = require('os');5const browser = await Playwright.chromium.launch();6const context = await browser.newContext();7const page = await context.newPage();8await page.close();9await context.close();10await browser.close();11const { Playwright } = require('playwright');12const path = require('path');13const fs = require('fs');14const os = require('os');15const browser = await Playwright.chromium.launch();16const context = await browser.newContext();17const page = await context.newPage();18await page.close();19await context.close();20await browser.close();21const { Playwright } = require('playwright');22const path = require('path');23const fs = require('fs');24const os = require('os');25const browser = await Playwright.chromium.launch();26const context = await browser.newContext();27const page = await context.newPage();28await page.close();29await context.close();30await browser.close();31const { Playwright } = require('playwright');32const path = require('path');33const fs = require('fs');34const os = require('os');35const browser = await Playwright.chromium.launch();36const context = await browser.newContext();37const page = await context.newPage();38await page.close();39await context.close();40await browser.close();41const { Playwright } = require('playwright');42const path = require('path');43const fs = require('fs');44const os = require('os');45const browser = await Playwright.chromium.launch();46const context = await browser.newContext();47const page = await context.newPage();48await page.close();49await context.close();50await browser.close();51const { Playwright } = require('playwright');52const path = require('path');53const fs = require('fs');54const os = require('os');55const browser = await Playwright.chromium.launch();56const context = await browser.newContext();57const page = await context.newPage();58await page.close();59await context.close();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { getPlaywright } = require('playwright-core');2const main = async () => {3 const playwright = await getPlaywright('chromium');4 const browser = await playwright.chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({ path: 'example.png' });8 await browser.close();9};10main();11const { getPlaywright } = require('playwright-core');12const main = async () => {13 const playwright = await getPlaywright('chromium');14 const browser = await playwright.chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.screenshot({ path: 'example.png' });18 await browser.close();19};20main();21const { getPlaywright } = require('playwright-core');22const main = async () => {23 const playwright = await getPlaywright('chromium');24 const browser = await playwright.chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 await page.screenshot({ path: 'example.png' });28 await browser.close();29};30main();31const { getPlaywright } = require('playwright-core');32const main = async () => {33 const playwright = await getPlaywright('chromium');34 const browser = await playwright.chromium.launch();35 const context = await browser.newContext();36 const page = await context.newPage();37 await page.screenshot({ path: 'example.png' });38 await browser.close();39};40main();41const { getPlaywright } = require('playwright-core');42const main = async () => {43 const playwright = await getPlaywright('chromium');44 const browser = await playwright.chromium.launch();45 const context = await browser.newContext();46 const page = await context.newPage();

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal 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