How to use model method in autotest

Best Python code snippet using autotest_python

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

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

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

Run autotest 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