Best JavaScript code snippet using devicefarmer-stf
duration.js
Source:duration.js
1import { module, test } from '../qunit';2import moment from '../../moment';3module('duration');4test('object instantiation', function (assert) {5 var d = moment.duration({6 years: 2,7 months: 3,8 weeks: 2,9 days: 1,10 hours: 8,11 minutes: 9,12 seconds: 20,13 milliseconds: 1214 });15 assert.equal(d.years(), 2, 'years');16 assert.equal(d.months(), 3, 'months');17 assert.equal(d.weeks(), 2, 'weeks');18 assert.equal(d.days(), 15, 'days'); // two weeks + 1 day19 assert.equal(d.hours(), 8, 'hours');20 assert.equal(d.minutes(), 9, 'minutes');21 assert.equal(d.seconds(), 20, 'seconds');22 assert.equal(d.milliseconds(), 12, 'milliseconds');23});24test('object instantiation with strings', function (assert) {25 var d = moment.duration({26 years: '2',27 months: '3',28 weeks: '2',29 days: '1',30 hours: '8',31 minutes: '9',32 seconds: '20',33 milliseconds: '12'34 });35 assert.equal(d.years(), 2, 'years');36 assert.equal(d.months(), 3, 'months');37 assert.equal(d.weeks(), 2, 'weeks');38 assert.equal(d.days(), 15, 'days'); // two weeks + 1 day39 assert.equal(d.hours(), 8, 'hours');40 assert.equal(d.minutes(), 9, 'minutes');41 assert.equal(d.seconds(), 20, 'seconds');42 assert.equal(d.milliseconds(), 12, 'milliseconds');43});44test('milliseconds instantiation', function (assert) {45 assert.equal(moment.duration(72).milliseconds(), 72, 'milliseconds');46 assert.equal(moment.duration(72).humanize(), 'a few seconds', 'Duration should be valid');47});48test('undefined instantiation', function (assert) {49 assert.equal(moment.duration(undefined).milliseconds(), 0, 'milliseconds');50 assert.equal(moment.duration(undefined).isValid(), true, '_isValid');51 assert.equal(moment.duration(undefined).humanize(), 'a few seconds', 'Duration should be valid');52});53test('null instantiation', function (assert) {54 assert.equal(moment.duration(null).milliseconds(), 0, 'milliseconds');55 assert.equal(moment.duration(null).isValid(), true, '_isValid');56 assert.equal(moment.duration(null).humanize(), 'a few seconds', 'Duration should be valid');57});58test('NaN instantiation', function (assert) {59 assert.ok(isNaN(moment.duration(NaN).milliseconds()), 'milliseconds should be NaN');60 assert.equal(moment.duration(NaN).isValid(), false, '_isValid');61 assert.equal(moment.duration(NaN).humanize(), 'Invalid date', 'Duration should be invalid');62});63test('instantiation by type', function (assert) {64 assert.equal(moment.duration(1, 'years').years(), 1, 'years');65 assert.equal(moment.duration(1, 'y').years(), 1, 'y');66 assert.equal(moment.duration(2, 'months').months(), 2, 'months');67 assert.equal(moment.duration(2, 'M').months(), 2, 'M');68 assert.equal(moment.duration(3, 'weeks').weeks(), 3, 'weeks');69 assert.equal(moment.duration(3, 'w').weeks(), 3, 'weeks');70 assert.equal(moment.duration(4, 'days').days(), 4, 'days');71 assert.equal(moment.duration(4, 'd').days(), 4, 'd');72 assert.equal(moment.duration(5, 'hours').hours(), 5, 'hours');73 assert.equal(moment.duration(5, 'h').hours(), 5, 'h');74 assert.equal(moment.duration(6, 'minutes').minutes(), 6, 'minutes');75 assert.equal(moment.duration(6, 'm').minutes(), 6, 'm');76 assert.equal(moment.duration(7, 'seconds').seconds(), 7, 'seconds');77 assert.equal(moment.duration(7, 's').seconds(), 7, 's');78 assert.equal(moment.duration(8, 'milliseconds').milliseconds(), 8, 'milliseconds');79 assert.equal(moment.duration(8, 'ms').milliseconds(), 8, 'ms');80});81test('shortcuts', function (assert) {82 assert.equal(moment.duration({y: 1}).years(), 1, 'years = y');83 assert.equal(moment.duration({M: 2}).months(), 2, 'months = M');84 assert.equal(moment.duration({w: 3}).weeks(), 3, 'weeks = w');85 assert.equal(moment.duration({d: 4}).days(), 4, 'days = d');86 assert.equal(moment.duration({h: 5}).hours(), 5, 'hours = h');87 assert.equal(moment.duration({m: 6}).minutes(), 6, 'minutes = m');88 assert.equal(moment.duration({s: 7}).seconds(), 7, 'seconds = s');89 assert.equal(moment.duration({ms: 8}).milliseconds(), 8, 'milliseconds = ms');90});91test('generic getter', function (assert) {92 assert.equal(moment.duration(1, 'years').get('years'), 1, 'years');93 assert.equal(moment.duration(1, 'years').get('year'), 1, 'years = year');94 assert.equal(moment.duration(1, 'years').get('y'), 1, 'years = y');95 assert.equal(moment.duration(2, 'months').get('months'), 2, 'months');96 assert.equal(moment.duration(2, 'months').get('month'), 2, 'months = month');97 assert.equal(moment.duration(2, 'months').get('M'), 2, 'months = M');98 assert.equal(moment.duration(3, 'weeks').get('weeks'), 3, 'weeks');99 assert.equal(moment.duration(3, 'weeks').get('week'), 3, 'weeks = week');100 assert.equal(moment.duration(3, 'weeks').get('w'), 3, 'weeks = w');101 assert.equal(moment.duration(4, 'days').get('days'), 4, 'days');102 assert.equal(moment.duration(4, 'days').get('day'), 4, 'days = day');103 assert.equal(moment.duration(4, 'days').get('d'), 4, 'days = d');104 assert.equal(moment.duration(5, 'hours').get('hours'), 5, 'hours');105 assert.equal(moment.duration(5, 'hours').get('hour'), 5, 'hours = hour');106 assert.equal(moment.duration(5, 'hours').get('h'), 5, 'hours = h');107 assert.equal(moment.duration(6, 'minutes').get('minutes'), 6, 'minutes');108 assert.equal(moment.duration(6, 'minutes').get('minute'), 6, 'minutes = minute');109 assert.equal(moment.duration(6, 'minutes').get('m'), 6, 'minutes = m');110 assert.equal(moment.duration(7, 'seconds').get('seconds'), 7, 'seconds');111 assert.equal(moment.duration(7, 'seconds').get('second'), 7, 'seconds = second');112 assert.equal(moment.duration(7, 'seconds').get('s'), 7, 'seconds = s');113 assert.equal(moment.duration(8, 'milliseconds').get('milliseconds'), 8, 'milliseconds');114 assert.equal(moment.duration(8, 'milliseconds').get('millisecond'), 8, 'milliseconds = millisecond');115 assert.equal(moment.duration(8, 'milliseconds').get('ms'), 8, 'milliseconds = ms');116});117test('instantiation from another duration', function (assert) {118 var simple = moment.duration(1234),119 lengthy = moment.duration(60 * 60 * 24 * 360 * 1e3),120 complicated = moment.duration({121 years: 2,122 months: 3,123 weeks: 4,124 days: 1,125 hours: 8,126 minutes: 9,127 seconds: 20,128 milliseconds: 12129 }),130 modified = moment.duration(1, 'day').add(moment.duration(1, 'day'));131 assert.deepEqual(moment.duration(simple), simple, 'simple clones are equal');132 assert.deepEqual(moment.duration(lengthy), lengthy, 'lengthy clones are equal');133 assert.deepEqual(moment.duration(complicated), complicated, 'complicated clones are equal');134 assert.deepEqual(moment.duration(modified), modified, 'cloning modified duration works');135});136test('explicit cloning', function (assert) {137 var durationA = moment.duration(5, 'milliseconds');138 var durationB = durationA.clone();139 durationA.add(5, 'milliseconds');140 assert.notEqual(durationA.milliseconds(), durationB.milliseconds(), 'Calling duration.clone() on a duration will create a clone');141});142test('instantiation from 24-hour time zero', function (assert) {143 assert.equal(moment.duration('00:00').years(), 0, '0 years');144 assert.equal(moment.duration('00:00').days(), 0, '0 days');145 assert.equal(moment.duration('00:00').hours(), 0, '0 hours');146 assert.equal(moment.duration('00:00').minutes(), 0, '0 minutes');147 assert.equal(moment.duration('00:00').seconds(), 0, '0 seconds');148 assert.equal(moment.duration('00:00').milliseconds(), 0, '0 milliseconds');149});150test('instantiation from 24-hour time <24 hours', function (assert) {151 assert.equal(moment.duration('06:45').years(), 0, '0 years');152 assert.equal(moment.duration('06:45').days(), 0, '0 days');153 assert.equal(moment.duration('06:45').hours(), 6, '6 hours');154 assert.equal(moment.duration('06:45').minutes(), 45, '45 minutes');155 assert.equal(moment.duration('06:45').seconds(), 0, '0 seconds');156 assert.equal(moment.duration('06:45').milliseconds(), 0, '0 milliseconds');157});158test('instantiation from 24-hour time >24 hours', function (assert) {159 assert.equal(moment.duration('26:45').years(), 0, '0 years');160 assert.equal(moment.duration('26:45').days(), 1, '0 days');161 assert.equal(moment.duration('26:45').hours(), 2, '2 hours');162 assert.equal(moment.duration('26:45').minutes(), 45, '45 minutes');163 assert.equal(moment.duration('26:45').seconds(), 0, '0 seconds');164 assert.equal(moment.duration('26:45').milliseconds(), 0, '0 milliseconds');165});166test('instantiation from serialized C# TimeSpan zero', function (assert) {167 assert.equal(moment.duration('00:00:00').years(), 0, '0 years');168 assert.equal(moment.duration('00:00:00').days(), 0, '0 days');169 assert.equal(moment.duration('00:00:00').hours(), 0, '0 hours');170 assert.equal(moment.duration('00:00:00').minutes(), 0, '0 minutes');171 assert.equal(moment.duration('00:00:00').seconds(), 0, '0 seconds');172 assert.equal(moment.duration('00:00:00').milliseconds(), 0, '0 milliseconds');173});174test('instantiation from serialized C# TimeSpan with days', function (assert) {175 assert.equal(moment.duration('1.02:03:04.9999999').years(), 0, '0 years');176 assert.equal(moment.duration('1.02:03:04.9999999').days(), 1, '1 day');177 assert.equal(moment.duration('1.02:03:04.9999999').hours(), 2, '2 hours');178 assert.equal(moment.duration('1.02:03:04.9999999').minutes(), 3, '3 minutes');179 assert.equal(moment.duration('1.02:03:04.9999999').seconds(), 5, '5 seconds');180 assert.equal(moment.duration('1.02:03:04.9999999').milliseconds(), 0, '0 milliseconds');181 assert.equal(moment.duration('1 02:03:04.9999999').years(), 0, '0 years');182 assert.equal(moment.duration('1 02:03:04.9999999').days(), 1, '1 day');183 assert.equal(moment.duration('1 02:03:04.9999999').hours(), 2, '2 hours');184 assert.equal(moment.duration('1 02:03:04.9999999').minutes(), 3, '3 minutes');185 assert.equal(moment.duration('1 02:03:04.9999999').seconds(), 5, '5 seconds');186 assert.equal(moment.duration('1 02:03:04.9999999').milliseconds(), 0, '0 milliseconds');187});188test('instantiation from serialized C# TimeSpan without days', function (assert) {189 assert.equal(moment.duration('01:02:03.9999999').years(), 0, '0 years');190 assert.equal(moment.duration('01:02:03.9999999').days(), 0, '0 days');191 assert.equal(moment.duration('01:02:03.9999999').hours(), 1, '1 hour');192 assert.equal(moment.duration('01:02:03.9999999').minutes(), 2, '2 minutes');193 assert.equal(moment.duration('01:02:03.9999999').seconds(), 4, '4 seconds');194 assert.equal(moment.duration('01:02:03.9999999').milliseconds(), 0, '0 milliseconds');195 assert.equal(moment.duration('23:59:59.9999999').days(), 1, '1 days');196 assert.equal(moment.duration('23:59:59.9999999').hours(), 0, '0 hours');197 assert.equal(moment.duration('23:59:59.9999999').minutes(), 0, '0 minutes');198 assert.equal(moment.duration('23:59:59.9999999').seconds(), 0, '0 seconds');199 assert.equal(moment.duration('23:59:59.9999999').milliseconds(), 0, '0 milliseconds');200 assert.equal(moment.duration('500:59:59.8888888').days(), 20, '500 hours overflows to 20 days');201 assert.equal(moment.duration('500:59:59.8888888').hours(), 20, '500 hours overflows to 20 hours');202});203test('instantiation from serialized C# TimeSpan without days or milliseconds', function (assert) {204 assert.equal(moment.duration('01:02:03').years(), 0, '0 years');205 assert.equal(moment.duration('01:02:03').days(), 0, '0 days');206 assert.equal(moment.duration('01:02:03').hours(), 1, '1 hour');207 assert.equal(moment.duration('01:02:03').minutes(), 2, '2 minutes');208 assert.equal(moment.duration('01:02:03').seconds(), 3, '3 seconds');209 assert.equal(moment.duration('01:02:03').milliseconds(), 0, '0 milliseconds');210});211test('instantiation from serialized C# TimeSpan without milliseconds', function (assert) {212 assert.equal(moment.duration('1.02:03:04').years(), 0, '0 years');213 assert.equal(moment.duration('1.02:03:04').days(), 1, '1 day');214 assert.equal(moment.duration('1.02:03:04').hours(), 2, '2 hours');215 assert.equal(moment.duration('1.02:03:04').minutes(), 3, '3 minutes');216 assert.equal(moment.duration('1.02:03:04').seconds(), 4, '4 seconds');217 assert.equal(moment.duration('1.02:03:04').milliseconds(), 0, '0 milliseconds');218});219test('instantiation from serialized C# TimeSpan with low millisecond precision', function (assert) {220 assert.equal(moment.duration('00:00:15.72').years(), 0, '0 years');221 assert.equal(moment.duration('00:00:15.72').days(), 0, '0 days');222 assert.equal(moment.duration('00:00:15.72').hours(), 0, '0 hours');223 assert.equal(moment.duration('00:00:15.72').minutes(), 0, '0 minutes');224 assert.equal(moment.duration('00:00:15.72').seconds(), 15, '15 seconds');225 assert.equal(moment.duration('00:00:15.72').milliseconds(), 720, '720 milliseconds');226 assert.equal(moment.duration('00:00:15.7').milliseconds(), 700, '700 milliseconds');227 assert.equal(moment.duration('00:00:15.').milliseconds(), 0, '0 milliseconds');228});229test('instantiation from serialized C# TimeSpan with high millisecond precision', function (assert) {230 assert.equal(moment.duration('00:00:15.7200000').seconds(), 15, '15 seconds');231 assert.equal(moment.duration('00:00:15.7200000').milliseconds(), 720, '720 milliseconds');232 assert.equal(moment.duration('00:00:15.7209999').seconds(), 15, '15 seconds');233 assert.equal(moment.duration('00:00:15.7209999').milliseconds(), 721, '721 milliseconds');234 assert.equal(moment.duration('00:00:15.7205000').seconds(), 15, '15 seconds');235 assert.equal(moment.duration('00:00:15.7205000').milliseconds(), 721, '721 milliseconds');236 assert.equal(moment.duration('-00:00:15.7205000').seconds(), -15, '15 seconds');237 assert.equal(moment.duration('-00:00:15.7205000').milliseconds(), -721, '721 milliseconds');238 assert.equal(moment.duration('+00:00:15.7205000').seconds(), 15, '15 seconds');239 assert.equal(moment.duration('+00:00:15.7205000').milliseconds(), 721, '721 milliseconds');240});241test('instantiation from serialized C# TimeSpan maxValue', function (assert) {242 var d = moment.duration('10675199.02:48:05.4775807');243 assert.equal(d.years(), 29227, '29227 years');244 assert.equal(d.months(), 8, '8 months');245 assert.equal(d.days(), 12, '12 day'); // if you have to change this value -- just do it246 assert.equal(d.hours(), 2, '2 hours');247 assert.equal(d.minutes(), 48, '48 minutes');248 assert.equal(d.seconds(), 5, '5 seconds');249 assert.equal(d.milliseconds(), 478, '478 milliseconds');250});251test('instantiation from serialized C# TimeSpan minValue', function (assert) {252 var d = moment.duration('-10675199.02:48:05.4775808');253 assert.equal(d.years(), -29227, '29653 years');254 assert.equal(d.months(), -8, '8 day');255 assert.equal(d.days(), -12, '12 day'); // if you have to change this value -- just do it256 assert.equal(d.hours(), -2, '2 hours');257 assert.equal(d.minutes(), -48, '48 minutes');258 assert.equal(d.seconds(), -5, '5 seconds');259 assert.equal(d.milliseconds(), -478, '478 milliseconds');260});261test('instantiation from serialized C# TimeSpan maxValue with + sign', function (assert) {262 var d = moment.duration('+10675199.02:48:05.4775808');263 assert.equal(d.years(), 29227, '29653 years');264 assert.equal(d.months(), 8, '8 day');265 assert.equal(d.days(), 12, '12 day'); // if you have to change this value -- just do it266 assert.equal(d.hours(), 2, '2 hours');267 assert.equal(d.minutes(), 48, '48 minutes');268 assert.equal(d.seconds(), 5, '5 seconds');269 assert.equal(d.milliseconds(), 478, '478 milliseconds');270});271test('instantiation from ISO 8601 duration', function (assert) {272 assert.equal(moment.duration('P1Y2M3DT4H5M6S').asSeconds(), moment.duration({y: 1, M: 2, d: 3, h: 4, m: 5, s: 6}).asSeconds(), 'all fields');273 assert.equal(moment.duration('P3W3D').asSeconds(), moment.duration({w: 3, d: 3}).asSeconds(), 'week and day fields');274 assert.equal(moment.duration('P1M').asSeconds(), moment.duration({M: 1}).asSeconds(), 'single month field');275 assert.equal(moment.duration('PT1M').asSeconds(), moment.duration({m: 1}).asSeconds(), 'single minute field');276 assert.equal(moment.duration('P1MT2H').asSeconds(), moment.duration({M: 1, h: 2}).asSeconds(), 'random fields missing');277 assert.equal(moment.duration('-P60D').asSeconds(), moment.duration({d: -60}).asSeconds(), 'negative days');278 assert.equal(moment.duration('+P60D').asSeconds(), moment.duration({d: 60}).asSeconds(), 'positive days');279 assert.equal(moment.duration('PT0.5S').asSeconds(), moment.duration({s: 0.5}).asSeconds(), 'fractional seconds');280 assert.equal(moment.duration('PT0,5S').asSeconds(), moment.duration({s: 0.5}).asSeconds(), 'fractional seconds (comma)');281});282test('serialization to ISO 8601 duration strings', function (assert) {283 assert.equal(moment.duration({y: 1, M: 2, d: 3, h: 4, m: 5, s: 6}).toISOString(), 'P1Y2M3DT4H5M6S', 'all fields');284 assert.equal(moment.duration({M: -1}).toISOString(), '-P1M', 'one month ago');285 assert.equal(moment.duration({m: -1}).toISOString(), '-PT1M', 'one minute ago');286 assert.equal(moment.duration({s: -0.5}).toISOString(), '-PT0.5S', 'one half second ago');287 assert.equal(moment.duration({y: -1, M: 1}).toISOString(), '-P11M', 'a month after a year ago');288 assert.equal(moment.duration({y: -1, h: 1}).toISOString(), '-P1YT-1H', 'an hour after a year ago');289 assert.equal(moment.duration({y: -1, h: 1, m: -1}).toISOString(), '-P1YT-59M', '59 minutes after a year ago');290 assert.equal(moment.duration({y: -1, h: 1, s: -1}).toISOString(), '-P1YT-59M-59S', '59 minutes 59 seconds after a year ago');291 assert.equal(moment.duration({y: -1, h: -1, s: 1}).toISOString(), '-P1YT59M59S', '59 minutes 59 seconds after a year ago');292 assert.equal(moment.duration({y: -1, d: 2}).toISOString(), '-P1Y-2D', '1 year less 2 days ago');293 assert.equal(moment.duration({M: +1}).toISOString(), 'P1M', 'one month ago');294 assert.equal(moment.duration({m: +1}).toISOString(), 'PT1M', 'one minute ago');295 assert.equal(moment.duration({s: +0.5}).toISOString(), 'PT0.5S', 'one half second ago');296 assert.equal(moment.duration({y: +1, M: 1}).toISOString(), 'P1Y1M', 'a month after a year in future');297 assert.equal(moment.duration({y: -1, h: 1}).toISOString(), '-P1YT-1H', 'an hour after a year ago');298 assert.equal(moment.duration({}).toISOString(), 'P0D', 'zero duration');299 assert.equal(moment.duration({M: 16, d:40, s: 86465}).toISOString(), 'P1Y4M40DT24H1M5S', 'all fields');300 assert.equal(moment.duration({ms: 123456789}).toISOString(), 'PT34H17M36.789S', 'check floating-point errors');301 assert.equal(moment.duration({ms: 31952}).toISOString(), 'PT31.952S', 'check floating-point errors');302});303test('toString acts as toISOString', function (assert) {304 assert.equal(moment.duration({y: 1, M: 2, d: 3, h: 4, m: 5, s: 6}).toString(), 'P1Y2M3DT4H5M6S', 'all fields');305 assert.equal(moment.duration({M: -1}).toString(), '-P1M', 'one month ago');306 assert.equal(moment.duration({m: -1}).toString(), '-PT1M', 'one minute ago');307 assert.equal(moment.duration({s: -0.5}).toString(), '-PT0.5S', 'one half second ago');308 assert.equal(moment.duration({y: -1, M: 1}).toString(), '-P11M', 'a month after a year ago');309 assert.equal(moment.duration({M: +1}).toString(), 'P1M', 'one month ago');310 assert.equal(moment.duration({m: +1}).toString(), 'PT1M', 'one minute ago');311 assert.equal(moment.duration({s: +0.5}).toString(), 'PT0.5S', 'one half second ago');312 assert.equal(moment.duration({y: +1, M: 1}).toString(), 'P1Y1M', 'a month after a year in future');313 assert.equal(moment.duration({}).toString(), 'P0D', 'zero duration');314 assert.equal(moment.duration({M: 16, d:40, s: 86465}).toString(), 'P1Y4M40DT24H1M5S', 'all fields');315});316test('toIsoString deprecation', function (assert) {317 test.expectedDeprecations('toIsoString()');318 assert.equal(moment.duration({}).toIsoString(), moment.duration({}).toISOString(), 'toIsoString delegates to toISOString');319});320test('`isodate` (python) test cases', function (assert) {321 assert.equal(moment.duration('P18Y9M4DT11H9M8S').asSeconds(), moment.duration({y: 18, M: 9, d: 4, h: 11, m: 9, s: 8}).asSeconds(), 'python isodate 1');322 assert.equal(moment.duration('P2W').asSeconds(), moment.duration({w: 2}).asSeconds(), 'python isodate 2');323 assert.equal(moment.duration('P3Y6M4DT12H30M5S').asSeconds(), moment.duration({y: 3, M: 6, d: 4, h: 12, m: 30, s: 5}).asSeconds(), 'python isodate 3');324 assert.equal(moment.duration('P23DT23H').asSeconds(), moment.duration({d: 23, h: 23}).asSeconds(), 'python isodate 4');325 assert.equal(moment.duration('P4Y').asSeconds(), moment.duration({y: 4}).asSeconds(), 'python isodate 5');326 assert.equal(moment.duration('P1M').asSeconds(), moment.duration({M: 1}).asSeconds(), 'python isodate 6');327 assert.equal(moment.duration('PT1M').asSeconds(), moment.duration({m: 1}).asSeconds(), 'python isodate 7');328 assert.equal(moment.duration('P0.5Y').asSeconds(), moment.duration({y: 0.5}).asSeconds(), 'python isodate 8');329 assert.equal(moment.duration('PT36H').asSeconds(), moment.duration({h: 36}).asSeconds(), 'python isodate 9');330 assert.equal(moment.duration('P1DT12H').asSeconds(), moment.duration({d: 1, h: 12}).asSeconds(), 'python isodate 10');331 assert.equal(moment.duration('-P2W').asSeconds(), moment.duration({w: -2}).asSeconds(), 'python isodate 11');332 assert.equal(moment.duration('-P2.2W').asSeconds(), moment.duration({w: -2.2}).asSeconds(), 'python isodate 12');333 assert.equal(moment.duration('+P2W').asSeconds(), moment.duration({w: 2}).asSeconds(), 'python isodate 11');334 assert.equal(moment.duration('+P2.2W').asSeconds(), moment.duration({w: 2.2}).asSeconds(), 'python isodate 12');335 assert.equal(moment.duration('P1DT2H3M4S').asSeconds(), moment.duration({d: 1, h: 2, m: 3, s: 4}).asSeconds(), 'python isodate 13');336 assert.equal(moment.duration('P1DT2H3M').asSeconds(), moment.duration({d: 1, h: 2, m: 3}).asSeconds(), 'python isodate 14');337 assert.equal(moment.duration('P1DT2H').asSeconds(), moment.duration({d: 1, h: 2}).asSeconds(), 'python isodate 15');338 assert.equal(moment.duration('PT2H').asSeconds(), moment.duration({h: 2}).asSeconds(), 'python isodate 16');339 assert.equal(moment.duration('PT2.3H').asSeconds(), moment.duration({h: 2.3}).asSeconds(), 'python isodate 17');340 assert.equal(moment.duration('PT2H3M4S').asSeconds(), moment.duration({h: 2, m: 3, s: 4}).asSeconds(), 'python isodate 18');341 assert.equal(moment.duration('PT3M4S').asSeconds(), moment.duration({m: 3, s: 4}).asSeconds(), 'python isodate 19');342 assert.equal(moment.duration('PT22S').asSeconds(), moment.duration({s: 22}).asSeconds(), 'python isodate 20');343 assert.equal(moment.duration('PT22.22S').asSeconds(), moment.duration({s: 22.22}).asSeconds(), 'python isodate 21');344 assert.equal(moment.duration('-P2Y').asSeconds(), moment.duration({y: -2}).asSeconds(), 'python isodate 22');345 assert.equal(moment.duration('-P3Y6M4DT12H30M5S').asSeconds(), moment.duration({y: -3, M: -6, d: -4, h: -12, m: -30, s: -5}).asSeconds(), 'python isodate 23');346 assert.equal(moment.duration('-P1DT2H3M4S').asSeconds(), moment.duration({d: -1, h: -2, m: -3, s: -4}).asSeconds(), 'python isodate 24');347 assert.equal(moment.duration('PT-6H3M').asSeconds(), moment.duration({h: -6, m: 3}).asSeconds(), 'python isodate 25');348 assert.equal(moment.duration('-PT-6H3M').asSeconds(), moment.duration({h: 6, m: -3}).asSeconds(), 'python isodate 26');349 assert.equal(moment.duration('-P-3Y-6M-4DT-12H-30M-5S').asSeconds(), moment.duration({y: 3, M: 6, d: 4, h: 12, m: 30, s: 5}).asSeconds(), 'python isodate 27');350 assert.equal(moment.duration('P-3Y-6M-4DT-12H-30M-5S').asSeconds(), moment.duration({y: -3, M: -6, d: -4, h: -12, m: -30, s: -5}).asSeconds(), 'python isodate 28');351 assert.equal(moment.duration('-P-2W').asSeconds(), moment.duration({w: 2}).asSeconds(), 'python isodate 29');352 assert.equal(moment.duration('P-2W').asSeconds(), moment.duration({w: -2}).asSeconds(), 'python isodate 30');353 assert.equal(moment.duration('+P2Y').asSeconds(), moment.duration({y: 2}).asSeconds(), 'python isodate 31');354 assert.equal(moment.duration('+P3Y6M4DT12H30M5S').asSeconds(), moment.duration({y: 3, M: 6, d: 4, h: 12, m: 30, s: 5}).asSeconds(), 'python isodate 32');355 assert.equal(moment.duration('+P1DT2H3M4S').asSeconds(), moment.duration({d: 1, h: 2, m: 3, s: 4}).asSeconds(), 'python isodate 34');356 assert.equal(moment.duration('PT+6H3M').asSeconds(), moment.duration({h: 6, m: 3}).asSeconds(), 'python isodate 35');357 assert.equal(moment.duration('+PT+6H3M').asSeconds(), moment.duration({h: 6, m: 3}).asSeconds(), 'python isodate 36');358 assert.equal(moment.duration('+PT-6H3M').asSeconds(), moment.duration({h: -6, m: 3}).asSeconds(), 'python isodate 37');359 assert.equal(moment.duration('+P+3Y+6M+4DT+12H+30M+5S').asSeconds(), moment.duration({y: 3, M: 6, d: 4, h: 12, m: 30, s: 5}).asSeconds(), 'python isodate 38');360 assert.equal(moment.duration('+P-3Y-6M-4DT-12H-30M-5S').asSeconds(), moment.duration({y: -3, M: -6, d: -4, h: -12, m: -30, s: -5}).asSeconds(), 'python isodate 39');361 assert.equal(moment.duration('P+3Y+6M+4DT+12H+30M+5S').asSeconds(), moment.duration({y: 3, M: 6, d: 4, h: 12, m: 30, s: 5}).asSeconds(), 'python isodate 40');362 assert.equal(moment.duration('+P+2W').asSeconds(), moment.duration({w: 2}).asSeconds(), 'python isodate 41');363 assert.equal(moment.duration('+P-2W').asSeconds(), moment.duration({w: -2}).asSeconds(), 'python isodate 41');364 assert.equal(moment.duration('P+2W').asSeconds(), moment.duration({w: 2}).asSeconds(), 'python isodate 43');365});366test('ISO 8601 misuse cases', function (assert) {367 assert.equal(moment.duration('P').asSeconds(), 0, 'lonely P');368 assert.equal(moment.duration('PT').asSeconds(), 0, 'just P and T');369 assert.equal(moment.duration('P1H').asSeconds(), 0, 'missing T');370 assert.equal(moment.duration('P1D1Y').asSeconds(), 0, 'out of order');371 assert.equal(moment.duration('PT.5S').asSeconds(), 0.5, 'accept no leading zero for decimal');372 assert.equal(moment.duration('PT1,S').asSeconds(), 1, 'accept trailing decimal separator');373 assert.equal(moment.duration('PT1M0,,5S').asSeconds(), 60, 'extra decimal separators are ignored as 0');374});375test('humanize', function (assert) {376 moment.locale('en');377 assert.equal(moment.duration({seconds: 44}).humanize(), 'a few seconds', '44 seconds = a few seconds');378 assert.equal(moment.duration({seconds: 45}).humanize(), 'a minute', '45 seconds = a minute');379 assert.equal(moment.duration({seconds: 89}).humanize(), 'a minute', '89 seconds = a minute');380 assert.equal(moment.duration({seconds: 90}).humanize(), '2 minutes', '90 seconds = 2 minutes');381 assert.equal(moment.duration({minutes: 44}).humanize(), '44 minutes', '44 minutes = 44 minutes');382 assert.equal(moment.duration({minutes: 45}).humanize(), 'an hour', '45 minutes = an hour');383 assert.equal(moment.duration({minutes: 89}).humanize(), 'an hour', '89 minutes = an hour');384 assert.equal(moment.duration({minutes: 90}).humanize(), '2 hours', '90 minutes = 2 hours');385 assert.equal(moment.duration({hours: 5}).humanize(), '5 hours', '5 hours = 5 hours');386 assert.equal(moment.duration({hours: 21}).humanize(), '21 hours', '21 hours = 21 hours');387 assert.equal(moment.duration({hours: 22}).humanize(), 'a day', '22 hours = a day');388 assert.equal(moment.duration({hours: 35}).humanize(), 'a day', '35 hours = a day');389 assert.equal(moment.duration({hours: 36}).humanize(), '2 days', '36 hours = 2 days');390 assert.equal(moment.duration({days: 1}).humanize(), 'a day', '1 day = a day');391 assert.equal(moment.duration({days: 5}).humanize(), '5 days', '5 days = 5 days');392 assert.equal(moment.duration({weeks: 1}).humanize(), '7 days', '1 week = 7 days');393 assert.equal(moment.duration({days: 25}).humanize(), '25 days', '25 days = 25 days');394 assert.equal(moment.duration({days: 26}).humanize(), 'a month', '26 days = a month');395 assert.equal(moment.duration({days: 30}).humanize(), 'a month', '30 days = a month');396 assert.equal(moment.duration({days: 45}).humanize(), 'a month', '45 days = a month');397 assert.equal(moment.duration({days: 46}).humanize(), '2 months', '46 days = 2 months');398 assert.equal(moment.duration({days: 74}).humanize(), '2 months', '74 days = 2 months');399 assert.equal(moment.duration({days: 77}).humanize(), '3 months', '77 days = 3 months');400 assert.equal(moment.duration({months: 1}).humanize(), 'a month', '1 month = a month');401 assert.equal(moment.duration({months: 5}).humanize(), '5 months', '5 months = 5 months');402 assert.equal(moment.duration({days: 344}).humanize(), 'a year', '344 days = a year');403 assert.equal(moment.duration({days: 345}).humanize(), 'a year', '345 days = a year');404 assert.equal(moment.duration({days: 547}).humanize(), 'a year', '547 days = a year');405 assert.equal(moment.duration({days: 548}).humanize(), '2 years', '548 days = 2 years');406 assert.equal(moment.duration({years: 1}).humanize(), 'a year', '1 year = a year');407 assert.equal(moment.duration({years: 5}).humanize(), '5 years', '5 years = 5 years');408 assert.equal(moment.duration(7200000).humanize(), '2 hours', '7200000 = 2 minutes');409});410test('humanize duration with suffix', function (assert) {411 moment.locale('en');412 assert.equal(moment.duration({seconds: 44}).humanize(true), 'in a few seconds', '44 seconds = a few seconds');413 assert.equal(moment.duration({seconds: -44}).humanize(true), 'a few seconds ago', '44 seconds = a few seconds');414 assert.equal(moment.duration({seconds: +44}).humanize(true), 'in a few seconds', '44 seconds = a few seconds');415});416test('bubble value up', function (assert) {417 assert.equal(moment.duration({milliseconds: 61001}).milliseconds(), 1, '61001 milliseconds has 1 millisecond left over');418 assert.equal(moment.duration({milliseconds: 61001}).seconds(), 1, '61001 milliseconds has 1 second left over');419 assert.equal(moment.duration({milliseconds: 61001}).minutes(), 1, '61001 milliseconds has 1 minute left over');420 assert.equal(moment.duration({minutes: 350}).minutes(), 50, '350 minutes has 50 minutes left over');421 assert.equal(moment.duration({minutes: 350}).hours(), 5, '350 minutes has 5 hours left over');422});423test('clipping', function (assert) {424 assert.equal(moment.duration({months: 11}).months(), 11, '11 months is 11 months');425 assert.equal(moment.duration({months: 11}).years(), 0, '11 months makes no year');426 assert.equal(moment.duration({months: 12}).months(), 0, '12 months is 0 months left over');427 assert.equal(moment.duration({months: 12}).years(), 1, '12 months makes 1 year');428 assert.equal(moment.duration({months: 13}).months(), 1, '13 months is 1 month left over');429 assert.equal(moment.duration({months: 13}).years(), 1, '13 months makes 1 year');430 assert.equal(moment.duration({days: 30}).days(), 30, '30 days is 30 days');431 assert.equal(moment.duration({days: 30}).months(), 0, '30 days makes no month');432 assert.equal(moment.duration({days: 31}).days(), 0, '31 days is 0 days left over');433 assert.equal(moment.duration({days: 31}).months(), 1, '31 days is a month');434 assert.equal(moment.duration({days: 32}).days(), 1, '32 days is 1 day left over');435 assert.equal(moment.duration({days: 32}).months(), 1, '32 days is a month');436 assert.equal(moment.duration({hours: 23}).hours(), 23, '23 hours is 23 hours');437 assert.equal(moment.duration({hours: 23}).days(), 0, '23 hours makes no day');438 assert.equal(moment.duration({hours: 24}).hours(), 0, '24 hours is 0 hours left over');439 assert.equal(moment.duration({hours: 24}).days(), 1, '24 hours makes 1 day');440 assert.equal(moment.duration({hours: 25}).hours(), 1, '25 hours is 1 hour left over');441 assert.equal(moment.duration({hours: 25}).days(), 1, '25 hours makes 1 day');442});443test('bubbling consistency', function (assert) {444 var days = 0, months = 0, newDays, newMonths, totalDays, d;445 for (totalDays = 1; totalDays <= 500; ++totalDays) {446 d = moment.duration(totalDays, 'days');447 newDays = d.days();448 newMonths = d.months() + d.years() * 12;449 assert.ok(450 (months === newMonths && days + 1 === newDays) ||451 (months + 1 === newMonths && newDays === 0),452 'consistent total days ' + totalDays +453 ' was ' + months + ' ' + days +454 ' now ' + newMonths + ' ' + newDays);455 days = newDays;456 months = newMonths;457 }458});459test('effective equivalency', function (assert) {460 assert.deepEqual(moment.duration({seconds: 1})._data, moment.duration({milliseconds: 1000})._data, '1 second is the same as 1000 milliseconds');461 assert.deepEqual(moment.duration({seconds: 60})._data, moment.duration({minutes: 1})._data, '1 minute is the same as 60 seconds');462 assert.deepEqual(moment.duration({minutes: 60})._data, moment.duration({hours: 1})._data, '1 hour is the same as 60 minutes');463 assert.deepEqual(moment.duration({hours: 24})._data, moment.duration({days: 1})._data, '1 day is the same as 24 hours');464 assert.deepEqual(moment.duration({days: 7})._data, moment.duration({weeks: 1})._data, '1 week is the same as 7 days');465 assert.deepEqual(moment.duration({days: 31})._data, moment.duration({months: 1})._data, '1 month is the same as 30 days');466 assert.deepEqual(moment.duration({months: 12})._data, moment.duration({years: 1})._data, '1 years is the same as 12 months');467});468test('asGetters', function (assert) {469 // 400 years have exactly 146097 days470 // years471 assert.equal(moment.duration(1, 'year').asYears(), 1, '1 year as years');472 assert.equal(moment.duration(1, 'year').asQuarters(), 4, '1 year as quarters');473 assert.equal(moment.duration(1, 'year').asMonths(), 12, '1 year as months');474 assert.equal(moment.duration(400, 'year').asMonths(), 4800, '400 years as months');475 assert.equal(moment.duration(1, 'year').asWeeks().toFixed(3), 52.143, '1 year as weeks');476 assert.equal(moment.duration(1, 'year').asDays(), 365, '1 year as days');477 assert.equal(moment.duration(2, 'year').asDays(), 730, '2 years as days');478 assert.equal(moment.duration(3, 'year').asDays(), 1096, '3 years as days');479 assert.equal(moment.duration(4, 'year').asDays(), 1461, '4 years as days');480 assert.equal(moment.duration(400, 'year').asDays(), 146097, '400 years as days');481 assert.equal(moment.duration(1, 'year').asHours(), 8760, '1 year as hours');482 assert.equal(moment.duration(1, 'year').asMinutes(), 525600, '1 year as minutes');483 assert.equal(moment.duration(1, 'year').asSeconds(), 31536000, '1 year as seconds');484 assert.equal(moment.duration(1, 'year').asMilliseconds(), 31536000000, '1 year as milliseconds');485 // quarters486 assert.equal(moment.duration(1, 'quarter').asYears(), 0.25, '1 quarter as years');487 assert.equal(moment.duration(1, 'quarter').asQuarters(), 1, '1 quarter as quarters');488 assert.equal(moment.duration(1, 'quarter').asMonths(), 3, '1 quarter as months');489 assert.equal(moment.duration(2, 'quarter').asWeeks().toFixed(3), 26.143, '2 month as quarters');490 assert.equal(moment.duration(1, 'quarter').asDays(), 91, '1 quarter as days');491 assert.equal(moment.duration(2, 'quarter').asDays(), 183, '2 quarter as days');492 assert.equal(moment.duration(3, 'quarter').asDays(), 274, '4 quarter as days');493 assert.equal(moment.duration(4, 'quarter').asDays(), 365, '4 quarter as days');494 assert.equal(moment.duration(1, 'quarter').asHours(), 2184, '1 quarter as hours');495 assert.equal(moment.duration(3, 'quarter').asHours(), 6576, '3 quarter as hours');496 assert.equal(moment.duration(2, 'quarter').asMinutes(), 263520, '2 quarter as minutes');497 assert.equal(moment.duration(3, 'quarter').asSeconds(), 23673600, '3 quarter as seconds');498 assert.equal(moment.duration(1, 'quarter').asMilliseconds(), 7862400000, '1 quarter as milliseconds');499 // months500 assert.equal(moment.duration(1, 'month').asYears().toFixed(4), 0.0833, '1 month as years');501 assert.equal(moment.duration(6, 'month').asQuarters(), 2, '6 month as quarters');502 assert.equal(moment.duration(1, 'month').asMonths(), 1, '1 month as months');503 assert.equal(moment.duration(1, 'month').asWeeks().toFixed(3), 4.286, '1 month as weeks');504 assert.equal(moment.duration(1, 'month').asDays(), 30, '1 month as days');505 assert.equal(moment.duration(2, 'month').asDays(), 61, '2 months as days');506 assert.equal(moment.duration(3, 'month').asDays(), 91, '3 months as days');507 assert.equal(moment.duration(4, 'month').asDays(), 122, '4 months as days');508 assert.equal(moment.duration(5, 'month').asDays(), 152, '5 months as days');509 assert.equal(moment.duration(6, 'month').asDays(), 183, '6 months as days');510 assert.equal(moment.duration(7, 'month').asDays(), 213, '7 months as days');511 assert.equal(moment.duration(8, 'month').asDays(), 243, '8 months as days');512 assert.equal(moment.duration(9, 'month').asDays(), 274, '9 months as days');513 assert.equal(moment.duration(10, 'month').asDays(), 304, '10 months as days');514 assert.equal(moment.duration(11, 'month').asDays(), 335, '11 months as days');515 assert.equal(moment.duration(12, 'month').asDays(), 365, '12 months as days');516 assert.equal(moment.duration(24, 'month').asDays(), 730, '24 months as days');517 assert.equal(moment.duration(36, 'month').asDays(), 1096, '36 months as days');518 assert.equal(moment.duration(48, 'month').asDays(), 1461, '48 months as days');519 assert.equal(moment.duration(4800, 'month').asDays(), 146097, '4800 months as days');520 assert.equal(moment.duration(1, 'month').asHours(), 720, '1 month as hours');521 assert.equal(moment.duration(1, 'month').asMinutes(), 43200, '1 month as minutes');522 assert.equal(moment.duration(1, 'month').asSeconds(), 2592000, '1 month as seconds');523 assert.equal(moment.duration(1, 'month').asMilliseconds(), 2592000000, '1 month as milliseconds');524 // weeks525 assert.equal(moment.duration(1, 'week').asYears().toFixed(4), 0.0192, '1 week as years');526 assert.equal(moment.duration(1, 'week').asQuarters().toFixed(4), 0.0767, '1 week as quarters');527 assert.equal(moment.duration(1, 'week').asMonths().toFixed(3), 0.230, '1 week as months');528 assert.equal(moment.duration(1, 'week').asWeeks(), 1, '1 week as weeks');529 assert.equal(moment.duration(1, 'week').asDays(), 7, '1 week as days');530 assert.equal(moment.duration(1, 'week').asHours(), 168, '1 week as hours');531 assert.equal(moment.duration(1, 'week').asMinutes(), 10080, '1 week as minutes');532 assert.equal(moment.duration(1, 'week').asSeconds(), 604800, '1 week as seconds');533 assert.equal(moment.duration(1, 'week').asMilliseconds(), 604800000, '1 week as milliseconds');534 // days535 assert.equal(moment.duration(1, 'day').asYears().toFixed(4), 0.0027, '1 day as years');536 assert.equal(moment.duration(1, 'day').asQuarters().toFixed(4), 0.0110, '1 day as quarters');537 assert.equal(moment.duration(1, 'day').asMonths().toFixed(3), 0.033, '1 day as months');538 assert.equal(moment.duration(1, 'day').asWeeks().toFixed(3), 0.143, '1 day as weeks');539 assert.equal(moment.duration(1, 'day').asDays(), 1, '1 day as days');540 assert.equal(moment.duration(1, 'day').asHours(), 24, '1 day as hours');541 assert.equal(moment.duration(1, 'day').asMinutes(), 1440, '1 day as minutes');542 assert.equal(moment.duration(1, 'day').asSeconds(), 86400, '1 day as seconds');543 assert.equal(moment.duration(1, 'day').asMilliseconds(), 86400000, '1 day as milliseconds');544 // hours545 assert.equal(moment.duration(1, 'hour').asYears().toFixed(6), 0.000114, '1 hour as years');546 assert.equal(moment.duration(1, 'hour').asQuarters().toFixed(6), 0.000456, '1 hour as quarters');547 assert.equal(moment.duration(1, 'hour').asMonths().toFixed(5), 0.00137, '1 hour as months');548 assert.equal(moment.duration(1, 'hour').asWeeks().toFixed(5), 0.00595, '1 hour as weeks');549 assert.equal(moment.duration(1, 'hour').asDays().toFixed(4), 0.0417, '1 hour as days');550 assert.equal(moment.duration(1, 'hour').asHours(), 1, '1 hour as hours');551 assert.equal(moment.duration(1, 'hour').asMinutes(), 60, '1 hour as minutes');552 assert.equal(moment.duration(1, 'hour').asSeconds(), 3600, '1 hour as seconds');553 assert.equal(moment.duration(1, 'hour').asMilliseconds(), 3600000, '1 hour as milliseconds');554 // minutes555 assert.equal(moment.duration(1, 'minute').asYears().toFixed(8), 0.00000190, '1 minute as years');556 assert.equal(moment.duration(1, 'minute').asQuarters().toFixed(8), 0.00000761, '1 minute as quarters');557 assert.equal(moment.duration(1, 'minute').asMonths().toFixed(7), 0.0000228, '1 minute as months');558 assert.equal(moment.duration(1, 'minute').asWeeks().toFixed(7), 0.0000992, '1 minute as weeks');559 assert.equal(moment.duration(1, 'minute').asDays().toFixed(6), 0.000694, '1 minute as days');560 assert.equal(moment.duration(1, 'minute').asHours().toFixed(4), 0.0167, '1 minute as hours');561 assert.equal(moment.duration(1, 'minute').asMinutes(), 1, '1 minute as minutes');562 assert.equal(moment.duration(1, 'minute').asSeconds(), 60, '1 minute as seconds');563 assert.equal(moment.duration(1, 'minute').asMilliseconds(), 60000, '1 minute as milliseconds');564 // seconds565 assert.equal(moment.duration(1, 'second').asYears().toFixed(10), 0.0000000317, '1 second as years');566 assert.equal(moment.duration(1, 'second').asQuarters().toFixed(10), 0.0000001268, '1 second as quarters');567 assert.equal(moment.duration(1, 'second').asMonths().toFixed(9), 0.000000380, '1 second as months');568 assert.equal(moment.duration(1, 'second').asWeeks().toFixed(8), 0.00000165, '1 second as weeks');569 assert.equal(moment.duration(1, 'second').asDays().toFixed(7), 0.0000116, '1 second as days');570 assert.equal(moment.duration(1, 'second').asHours().toFixed(6), 0.000278, '1 second as hours');571 assert.equal(moment.duration(1, 'second').asMinutes().toFixed(4), 0.0167, '1 second as minutes');572 assert.equal(moment.duration(1, 'second').asSeconds(), 1, '1 second as seconds');573 assert.equal(moment.duration(1, 'second').asMilliseconds(), 1000, '1 second as milliseconds');574 // milliseconds575 assert.equal(moment.duration(1, 'millisecond').asYears().toFixed(13), 0.0000000000317, '1 millisecond as years');576 assert.equal(moment.duration(1, 'millisecond').asQuarters().toFixed(13), 0.0000000001268, '1 millisecond as quarters');577 assert.equal(moment.duration(1, 'millisecond').asMonths().toFixed(12), 0.000000000380, '1 millisecond as months');578 assert.equal(moment.duration(1, 'millisecond').asWeeks().toFixed(11), 0.00000000165, '1 millisecond as weeks');579 assert.equal(moment.duration(1, 'millisecond').asDays().toFixed(10), 0.0000000116, '1 millisecond as days');580 assert.equal(moment.duration(1, 'millisecond').asHours().toFixed(9), 0.000000278, '1 millisecond as hours');581 assert.equal(moment.duration(1, 'millisecond').asMinutes().toFixed(7), 0.0000167, '1 millisecond as minutes');582 assert.equal(moment.duration(1, 'millisecond').asSeconds(), 0.001, '1 millisecond as seconds');583 assert.equal(moment.duration(1, 'millisecond').asMilliseconds(), 1, '1 millisecond as milliseconds');584});585test('as getters for small units', function (assert) {586 var dS = moment.duration(1, 'milliseconds'),587 ds = moment.duration(3, 'seconds'),588 dm = moment.duration(13, 'minutes');589 // Tests for issue #1867.590 // Floating point errors for small duration units were introduced in version 2.8.0.591 assert.equal(dS.as('milliseconds'), 1, 'as("milliseconds")');592 assert.equal(dS.asMilliseconds(), 1, 'asMilliseconds()');593 assert.equal(ds.as('seconds'), 3, 'as("seconds")');594 assert.equal(ds.asSeconds(), 3, 'asSeconds()');595 assert.equal(dm.as('minutes'), 13, 'as("minutes")');596 assert.equal(dm.asMinutes(), 13, 'asMinutes()');597});598test('minutes getter for floating point hours', function (assert) {599 // Tests for issue #2978.600 // For certain floating point hours, .minutes() getter produced incorrect values due to the rounding errors601 assert.equal(moment.duration(2.3, 'h').minutes(), 18, 'minutes()');602 assert.equal(moment.duration(4.1, 'h').minutes(), 6, 'minutes()');603});604test('isDuration', function (assert) {605 assert.ok(moment.isDuration(moment.duration(12345678)), 'correctly says true');606 assert.ok(!moment.isDuration(moment()), 'moment object is not a duration');607 assert.ok(!moment.isDuration({milliseconds: 1}), 'plain object is not a duration');608});609test('add', function (assert) {610 var d = moment.duration({months: 4, weeks: 3, days: 2});611 // for some reason, d._data._months does not get updated; use d._months instead.612 assert.equal(d.add(1, 'month')._months, 5, 'Add months');613 assert.equal(d.add(5, 'days')._days, 28, 'Add days');614 assert.equal(d.add(10000)._milliseconds, 10000, 'Add milliseconds');615 assert.equal(d.add({h: 23, m: 59})._milliseconds, 23 * 60 * 60 * 1000 + 59 * 60 * 1000 + 10000, 'Add hour:minute');616});617test('add to moment', function (assert) {618 var d = moment.duration({months: 1, seconds: -1});619 var m = moment('2017-03-01').add(d);620 assert.equal(m.month(), 2, 'Adds months before time');621 assert.equal(m.date(), 31, 'Adds time after months');622});623test('add and bubble', function (assert) {624 var d;625 assert.equal(moment.duration(1, 'second').add(1000, 'milliseconds').seconds(), 2, 'Adding milliseconds should bubble up to seconds');626 assert.equal(moment.duration(1, 'minute').add(60, 'second').minutes(), 2, 'Adding seconds should bubble up to minutes');627 assert.equal(moment.duration(1, 'hour').add(60, 'minutes').hours(), 2, 'Adding minutes should bubble up to hours');628 assert.equal(moment.duration(1, 'day').add(24, 'hours').days(), 2, 'Adding hours should bubble up to days');629 d = moment.duration(-1, 'day').add(1, 'hour');630 assert.equal(d.hours(), -23, '-1 day + 1 hour == -23 hour (component)');631 assert.equal(d.asHours(), -23, '-1 day + 1 hour == -23 hours');632 d = moment.duration(+1, 'day').add(1, 'hour');633 assert.equal(d.hours(), 1, '1 day + 1 hour == 1 hour (component)');634 assert.equal(d.asHours(), 25, '1 day + 1 hour == 25 hour');635 d = moment.duration(-1, 'year').add(1, 'day');636 assert.equal(d.days(), -30, '- 1 year + 1 day == -30 days (component)');637 assert.equal(d.months(), -11, '- 1 year + 1 day == -11 months (component)');638 assert.equal(d.years(), 0, '- 1 year + 1 day == 0 years (component)');639 assert.equal(d.asDays(), -364, '- 1 year + 1 day == -364 days');640 d = moment.duration(+1, 'year').add(1, 'day');641 assert.equal(d.days(), 1, '+ 1 year + 1 day == 1 days (component)');642 assert.equal(d.months(), 0, '+ 1 year + 1 day == 0 month (component)');643 assert.equal(d.years(), 1, '+ 1 year + 1 day == 1 year (component)');644 assert.equal(d.asDays(), 366, '+ 1 year + 1 day == +366 day');645 d = moment.duration(-1, 'year').add(1, 'hour');646 assert.equal(d.hours(), -23, '- 1 year + 1 hour == -23 hours (component)');647 assert.equal(d.days(), -30, '- 1 year + 1 hour == -30 days (component)');648 assert.equal(d.months(), -11, '- 1 year + 1 hour == -11 months (component)');649 assert.equal(d.years(), 0, '- 1 year + 1 hour == 0 years (component)');650 d = moment.duration(+1, 'year').add(1, 'hour');651 assert.equal(d.hours(), 1, '+ 1 year + 1 hour == 1 hour (component)');652 assert.equal(d.days(), 0, '+ 1 year + 1 hour == 1 day (component)');653 assert.equal(d.months(), 0, '+ 1 year + 1 hour == 1 month (component)');654 assert.equal(d.years(), 1, '+ 1 year + 1 hour == 1 year (component)');655});656test('subtract and bubble', function (assert) {657 var d;658 assert.equal(moment.duration(2, 'second').subtract(1000, 'milliseconds').seconds(), 1, 'Subtracting milliseconds should bubble up to seconds');659 assert.equal(moment.duration(2, 'minute').subtract(60, 'second').minutes(), 1, 'Subtracting seconds should bubble up to minutes');660 assert.equal(moment.duration(2, 'hour').subtract(60, 'minutes').hours(), 1, 'Subtracting minutes should bubble up to hours');661 assert.equal(moment.duration(2, 'day').subtract(24, 'hours').days(), 1, 'Subtracting hours should bubble up to days');662 d = moment.duration(1, 'day').subtract(1, 'hour');663 assert.equal(d.hours(), 23, '1 day - 1 hour == 23 hour (component)');664 assert.equal(d.asHours(), 23, '1 day - 1 hour == 23 hours');665 d = moment.duration(1, 'year').subtract(1, 'day');666 assert.equal(d.days(), 30, '1 year - 1 day == 30 days (component)');667 assert.equal(d.months(), 11, '1 year - 1 day == 11 months (component)');668 assert.equal(d.years(), 0, '1 year - 1 day == 0 years (component)');669 assert.equal(d.asDays(), 364, '1 year - 1 day == 364 days');670 d = moment.duration(1, 'year').subtract(1, 'hour');671 assert.equal(d.hours(), 23, '1 year - 1 hour == 23 hours (component)');672 assert.equal(d.days(), 30, '1 year - 1 hour == 30 days (component)');673 assert.equal(d.months(), 11, '1 year - 1 hour == 11 months (component)');674 assert.equal(d.years(), 0, '1 year - 1 hour == 0 years (component)');675});676test('subtract', function (assert) {677 var d = moment.duration({months: 2, weeks: 2, days: 0, hours: 5});678 // for some reason, d._data._months does not get updated; use d._months instead.679 assert.equal(d.subtract(1, 'months')._months, 1, 'Subtract months');680 assert.equal(d.subtract(14, 'days')._days, 0, 'Subtract days');681 assert.equal(d.subtract(10000)._milliseconds, 5 * 60 * 60 * 1000 - 10000, 'Subtract milliseconds');682 assert.equal(d.subtract({h: 1, m: 59})._milliseconds, 3 * 60 * 60 * 1000 + 1 * 60 * 1000 - 10000, 'Subtract hour:minute');683});684test('JSON.stringify duration', function (assert) {685 var d = moment.duration(1024, 'h');686 assert.equal(JSON.stringify(d), '"' + d.toISOString() + '"', 'JSON.stringify on duration should return ISO string');687});688test('duration plugins', function (assert) {689 var durationObject = moment.duration();690 moment.duration.fn.foo = function (arg) {691 assert.equal(this, durationObject);692 assert.equal(arg, 5);693 };694 durationObject.foo(5);...
MovieCamera.py
Source:MovieCamera.py
1from pandac.PandaModules import *2from direct.interval.IntervalGlobal import *3from BattleBase import *4from BattleProps import *5from toontown.toonbase.ToontownBattleGlobals import *6from SuitBattleGlobals import *7from direct.directnotify import DirectNotifyGlobal8import random9import MovieUtil10notify = DirectNotifyGlobal.directNotify.newCategory('MovieCamera')11def chooseHealShot(heals, attackDuration):12 isUber = 013 for heal in heals:14 if heal['level'] == 6 and not heal.get('petId'):15 isUber = 116 if isUber:17 openShot = chooseHealOpenShot(heals, attackDuration, isUber)18 openDuration = openShot.getDuration()19 openName = openShot.getName()20 closeShot = chooseHealCloseShot(heals, openDuration, openName, attackDuration * 3, isUber)21 track = Sequence(closeShot)22 else:23 openShot = chooseHealOpenShot(heals, attackDuration, isUber)24 openDuration = openShot.getDuration()25 openName = openShot.getName()26 closeShot = chooseHealCloseShot(heals, openDuration, openName, attackDuration, isUber)27 track = Sequence(openShot, closeShot)28 return track29def chooseHealOpenShot(heals, attackDuration, isUber = 0):30 numHeals = len(heals)31 av = None32 duration = 2.833 if isUber:34 duration = 5.035 shotChoices = [toonGroupShot]36 track = apply(random.choice(shotChoices), [av, duration])37 return track38def chooseHealMidShot(heals, attackDuration, isUber = 0):39 numHeals = len(heals)40 av = None41 duration = 2.142 if isUber:43 duration = 2.144 shotChoices = [toonGroupHighShot]45 track = apply(random.choice(shotChoices), [av, duration])46 return track47def chooseHealCloseShot(heals, openDuration, openName, attackDuration, isUber = 0):48 av = None49 duration = attackDuration - openDuration50 shotChoices = [toonGroupShot]51 if isUber:52 shotChoices = [allGroupLowShot]53 track = apply(random.choice(shotChoices), [av, duration])54 return track55def chooseTrapShot(traps, attackDuration, enterDuration = 0, exitDuration = 0):56 enterShot = chooseNPCEnterShot(traps, enterDuration)57 openShot = chooseTrapOpenShot(traps, attackDuration)58 openDuration = openShot.getDuration()59 openName = openShot.getName()60 closeShot = chooseTrapCloseShot(traps, openDuration, openName, attackDuration)61 exitShot = chooseNPCExitShot(traps, exitDuration)62 track = Sequence(enterShot, openShot, closeShot, exitShot)63 return track64def chooseTrapOpenShot(traps, attackDuration):65 numTraps = len(traps)66 av = None67 duration = 3.068 shotChoices = [allGroupLowShot]69 track = apply(random.choice(shotChoices), [av, duration])70 return track71def chooseTrapCloseShot(traps, openDuration, openName, attackDuration):72 av = None73 duration = attackDuration - openDuration74 shotChoices = [allGroupLowShot]75 track = apply(random.choice(shotChoices), [av, duration])76 return track77def chooseLureShot(lures, attackDuration, enterDuration = 0.0, exitDuration = 0.0):78 enterShot = chooseNPCEnterShot(lures, enterDuration)79 openShot = chooseLureOpenShot(lures, attackDuration)80 openDuration = openShot.getDuration()81 openName = openShot.getName()82 closeShot = chooseLureCloseShot(lures, openDuration, openName, attackDuration)83 exitShot = chooseNPCExitShot(lures, exitDuration)84 track = Sequence(enterShot, openShot, closeShot, exitShot)85 return track86def chooseLureOpenShot(lures, attackDuration):87 numLures = len(lures)88 av = None89 duration = 3.090 shotChoices = [allGroupLowShot]91 track = apply(random.choice(shotChoices), [av, duration])92 return track93def chooseLureCloseShot(lures, openDuration, openName, attackDuration):94 av = None95 duration = attackDuration - openDuration96 hasTrainTrackTrap = False97 battle = lures[0]['battle']98 for suit in battle.suits:99 if hasattr(suit, 'battleTrap') and suit.battleTrap == UBER_GAG_LEVEL_INDEX:100 hasTrainTrackTrap = True101 if hasTrainTrackTrap:102 shotChoices = [avatarBehindHighRightShot]103 av = lures[0]['toon']104 else:105 shotChoices = [allGroupLowShot]106 track = apply(random.choice(shotChoices), [av, duration])107 return track108def chooseSoundShot(sounds, targets, attackDuration, enterDuration = 0.0, exitDuration = 0.0):109 enterShot = chooseNPCEnterShot(sounds, enterDuration)110 openShot = chooseSoundOpenShot(sounds, targets, attackDuration)111 openDuration = openShot.getDuration()112 openName = openShot.getName()113 closeShot = chooseSoundCloseShot(sounds, targets, openDuration, openName, attackDuration)114 exitShot = chooseNPCExitShot(sounds, exitDuration)115 track = Sequence(enterShot, openShot, closeShot, exitShot)116 return track117def chooseSoundOpenShot(sounds, targets, attackDuration):118 duration = 3.1119 isUber = 0120 for sound in sounds:121 if sound['level'] == 6:122 isUber = 1123 duration = 5.0124 numSounds = len(sounds)125 av = None126 if numSounds == 1:127 av = sounds[0]['toon']128 if isUber:129 shotChoices = [avatarCloseUpThreeQuarterRightShotWide, allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]130 else:131 shotChoices = [avatarCloseUpThreeQuarterRightShot, allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]132 elif numSounds >= 2 and numSounds <= 4:133 shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]134 else:135 notify.error('Bad number of sounds: %s' % numSounds)136 track = apply(random.choice(shotChoices), [av, duration])137 return track138def chooseSoundCloseShot(sounds, targets, openDuration, openName, attackDuration):139 numSuits = len(targets)140 av = None141 duration = attackDuration - openDuration142 if numSuits == 1:143 av = targets[0]['suit']144 shotChoices = [avatarCloseUpThrowShot,145 avatarCloseUpThreeQuarterLeftShot,146 allGroupLowShot,147 suitGroupThreeQuarterLeftBehindShot]148 elif numSuits >= 2 and numSuits <= 4:149 shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]150 else:151 notify.error('Bad number of suits: %s' % numSuits)152 track = apply(random.choice(shotChoices), [av, duration])153 return track154def chooseThrowShot(throws, suitThrowsDict, attackDuration):155 openShot = chooseThrowOpenShot(throws, suitThrowsDict, attackDuration)156 openDuration = openShot.getDuration()157 openName = openShot.getName()158 closeShot = chooseThrowCloseShot(throws, suitThrowsDict, openDuration, openName, attackDuration)159 track = Sequence(openShot, closeShot)160 return track161def chooseThrowOpenShot(throws, suitThrowsDict, attackDuration):162 numThrows = len(throws)163 av = None164 duration = 3.0165 if numThrows == 1:166 av = throws[0]['toon']167 shotChoices = [avatarCloseUpThrowShot,168 avatarCloseUpThreeQuarterRightShot,169 avatarBehindShot,170 allGroupLowShot,171 suitGroupThreeQuarterLeftBehindShot]172 elif numThrows >= 2 and numThrows <= 4:173 shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]174 else:175 notify.error('Bad number of throws: %s' % numThrows)176 track = apply(random.choice(shotChoices), [av, duration])177 return track178def chooseThrowCloseShot(throws, suitThrowsDict, openDuration, openName, attackDuration):179 numSuits = len(suitThrowsDict)180 av = None181 duration = attackDuration - openDuration182 if numSuits == 1:183 av = base.cr.doId2do[suitThrowsDict.keys()[0]]184 shotChoices = [avatarCloseUpThrowShot,185 avatarCloseUpThreeQuarterLeftShot,186 allGroupLowShot,187 suitGroupThreeQuarterLeftBehindShot]188 elif numSuits >= 2 and numSuits <= 4 or numSuits == 0:189 shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]190 else:191 notify.error('Bad number of suits: %s' % numSuits)192 track = apply(random.choice(shotChoices), [av, duration])193 return track194def chooseSquirtShot(squirts, suitSquirtsDict, attackDuration):195 openShot = chooseSquirtOpenShot(squirts, suitSquirtsDict, attackDuration)196 openDuration = openShot.getDuration()197 openName = openShot.getName()198 closeShot = chooseSquirtCloseShot(squirts, suitSquirtsDict, openDuration, openName, attackDuration)199 track = Sequence(openShot, closeShot)200 return track201def chooseSquirtOpenShot(squirts, suitSquirtsDict, attackDuration):202 numSquirts = len(squirts)203 av = None204 duration = 3.0205 if numSquirts == 1:206 av = squirts[0]['toon']207 shotChoices = [avatarCloseUpThrowShot,208 avatarCloseUpThreeQuarterRightShot,209 avatarBehindShot,210 allGroupLowShot,211 suitGroupThreeQuarterLeftBehindShot]212 elif numSquirts >= 2 and numSquirts <= 4:213 shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]214 else:215 notify.error('Bad number of squirts: %s' % numSquirts)216 track = apply(random.choice(shotChoices), [av, duration])217 return track218def chooseSquirtCloseShot(squirts, suitSquirtsDict, openDuration, openName, attackDuration):219 numSuits = len(suitSquirtsDict)220 av = None221 duration = attackDuration - openDuration222 if numSuits == 1:223 av = base.cr.doId2do[suitSquirtsDict.keys()[0]]224 shotChoices = [avatarCloseUpThrowShot,225 avatarCloseUpThreeQuarterLeftShot,226 allGroupLowShot,227 suitGroupThreeQuarterLeftBehindShot]228 elif numSuits >= 2 and numSuits <= 4:229 shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]230 else:231 notify.error('Bad number of suits: %s' % numSuits)232 track = apply(random.choice(shotChoices), [av, duration])233 return track234def chooseDropShot(drops, suitDropsDict, attackDuration, enterDuration = 0.0, exitDuration = 0.0):235 enterShot = chooseNPCEnterShot(drops, enterDuration)236 openShot = chooseDropOpenShot(drops, suitDropsDict, attackDuration)237 openDuration = openShot.getDuration()238 openName = openShot.getName()239 closeShot = chooseDropCloseShot(drops, suitDropsDict, openDuration, openName, attackDuration)240 exitShot = chooseNPCExitShot(drops, exitDuration)241 track = Sequence(enterShot, openShot, closeShot, exitShot)242 return track243def chooseDropOpenShot(drops, suitDropsDict, attackDuration):244 numDrops = len(drops)245 av = None246 duration = 3.0247 if numDrops == 1:248 av = drops[0]['toon']249 shotChoices = [avatarCloseUpThrowShot,250 avatarCloseUpThreeQuarterRightShot,251 avatarBehindShot,252 allGroupLowShot,253 suitGroupThreeQuarterLeftBehindShot]254 elif numDrops >= 2 and numDrops <= 4 or numDrops == 0:255 shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]256 else:257 notify.error('Bad number of drops: %s' % numDrops)258 track = apply(random.choice(shotChoices), [av, duration])259 return track260def chooseDropCloseShot(drops, suitDropsDict, openDuration, openName, attackDuration):261 numSuits = len(suitDropsDict)262 av = None263 duration = attackDuration - openDuration264 if numSuits == 1:265 av = base.cr.doId2do[suitDropsDict.keys()[0]]266 shotChoices = [avatarCloseUpThrowShot,267 avatarCloseUpThreeQuarterLeftShot,268 allGroupLowShot,269 suitGroupThreeQuarterLeftBehindShot]270 elif numSuits >= 2 and numSuits <= 4 or numSuits == 0:271 shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]272 else:273 notify.error('Bad number of suits: %s' % numSuits)274 choice = random.choice(shotChoices)275 track = choice(av, duration)276 return track277def chooseNPCEnterShot(enters, entersDuration):278 av = None279 duration = entersDuration280 shotChoices = [toonGroupShot]281 track = apply(random.choice(shotChoices), [av, duration])282 return track283def chooseNPCExitShot(exits, exitsDuration):284 av = None285 duration = exitsDuration286 shotChoices = [toonGroupShot]287 track = apply(random.choice(shotChoices), [av, duration])288 return track289def chooseSuitShot(attack, attackDuration):290 groupStatus = attack['group']291 target = attack['target']292 if groupStatus == ATK_TGT_SINGLE:293 toon = target['toon']294 suit = attack['suit']295 name = attack['id']296 battle = attack['battle']297 camTrack = Sequence()298 def defaultCamera(attack = attack, attackDuration = attackDuration, openShotDuration = 3.5, target = target):299 if attack['group'] == ATK_TGT_GROUP:300 return randomGroupAttackCam(attack['suit'], target, attack['battle'], attackDuration, openShotDuration)301 else:302 return randomAttackCam(attack['suit'], target['toon'], attack['battle'], attackDuration, openShotDuration, 'suit')303 if name == AUDIT:304 camTrack.append(defaultCamera())305 elif name == BITE:306 camTrack.append(defaultCamera(openShotDuration=2.8))307 elif name == BOUNCE_CHECK:308 camTrack.append(defaultCamera())309 elif name == BRAIN_STORM:310 camTrack.append(defaultCamera(openShotDuration=2.4))311 elif name == BUZZ_WORD:312 camTrack.append(defaultCamera(openShotDuration=4.7))313 elif name == CALCULATE:314 camTrack.append(defaultCamera())315 elif name == CANNED:316 camTrack.append(defaultCamera(openShotDuration=2.9))317 elif name == CHOMP:318 camTrack.append(defaultCamera(openShotDuration=2.8))319 elif name == CLIPON_TIE:320 camTrack.append(defaultCamera(openShotDuration=3.3))321 elif name == CRUNCH:322 camTrack.append(defaultCamera(openShotDuration=3.4))323 elif name == DEMOTION:324 camTrack.append(defaultCamera(openShotDuration=1.7))325 elif name == DOUBLE_TALK:326 camTrack.append(defaultCamera(openShotDuration=3.9))327 elif name == EVICTION_NOTICE:328 camTrack.append(defaultCamera(openShotDuration=3.2))329 elif name == EVIL_EYE:330 camTrack.append(defaultCamera(openShotDuration=2.7))331 elif name == FILIBUSTER:332 camTrack.append(defaultCamera(openShotDuration=2.7))333 elif name == FILL_WITH_LEAD:334 camTrack.append(defaultCamera(openShotDuration=3.2))335 elif name == FINGER_WAG:336 camTrack.append(defaultCamera(openShotDuration=2.3))337 elif name == FIRED:338 camTrack.append(defaultCamera(openShotDuration=1.7))339 elif name == FOUNTAIN_PEN:340 camTrack.append(defaultCamera(openShotDuration=2.6))341 elif name == FREEZE_ASSETS:342 camTrack.append(defaultCamera(openShotDuration=2.5))343 elif name == HALF_WINDSOR:344 camTrack.append(defaultCamera(openShotDuration=2.8))345 elif name == HEAD_SHRINK:346 camTrack.append(defaultCamera(openShotDuration=1.3))347 elif name == GLOWER_POWER:348 camTrack.append(defaultCamera(openShotDuration=1.4))349 elif name == GUILT_TRIP:350 camTrack.append(defaultCamera(openShotDuration=0.9))351 elif name == HANG_UP:352 camTrack.append(defaultCamera(openShotDuration=5.1))353 elif name == HOT_AIR:354 camTrack.append(defaultCamera(openShotDuration=2.5))355 elif name == JARGON:356 camTrack.append(defaultCamera())357 elif name == LEGALESE:358 camTrack.append(defaultCamera(openShotDuration=1.5))359 elif name == LIQUIDATE:360 camTrack.append(defaultCamera(openShotDuration=2.5))361 elif name == MARKET_CRASH:362 camTrack.append(defaultCamera(openShotDuration=2.9))363 elif name == MUMBO_JUMBO:364 camTrack.append(defaultCamera(openShotDuration=2.8))365 elif name == PARADIGM_SHIFT:366 camTrack.append(defaultCamera(openShotDuration=1.6))367 elif name == PECKING_ORDER:368 camTrack.append(defaultCamera(openShotDuration=2.8))369 elif name == PLAY_HARDBALL:370 camTrack.append(defaultCamera(openShotDuration=2.3))371 elif name == PICK_POCKET:372 camTrack.append(allGroupLowShot(suit, 2.7))373 elif name == PINK_SLIP:374 camTrack.append(defaultCamera(openShotDuration=2.8))375 elif name == POUND_KEY:376 camTrack.append(defaultCamera(openShotDuration=2.8))377 elif name == POWER_TIE:378 camTrack.append(defaultCamera(openShotDuration=2.4))379 elif name == POWER_TRIP:380 camTrack.append(defaultCamera(openShotDuration=1.1))381 elif name == QUAKE:382 shakeIntensity = 5.15383 quake = 1384 camTrack.append(suitCameraShakeShot(suit, attackDuration, shakeIntensity, quake))385 elif name == RAZZLE_DAZZLE:386 camTrack.append(defaultCamera(openShotDuration=2.2))387 elif name == RED_TAPE:388 camTrack.append(defaultCamera(openShotDuration=3.5))389 elif name == RE_ORG:390 camTrack.append(defaultCamera(openShotDuration=1.1))391 elif name == RESTRAINING_ORDER:392 camTrack.append(defaultCamera(openShotDuration=2.8))393 elif name == ROLODEX:394 camTrack.append(defaultCamera())395 elif name == RUBBER_STAMP:396 camTrack.append(defaultCamera(openShotDuration=3.2))397 elif name == RUB_OUT:398 camTrack.append(defaultCamera(openShotDuration=2.2))399 elif name == SACKED:400 camTrack.append(defaultCamera(openShotDuration=2.9))401 elif name == SCHMOOZE:402 camTrack.append(defaultCamera(openShotDuration=2.8))403 elif name == SHAKE:404 shakeIntensity = 1.75405 camTrack.append(suitCameraShakeShot(suit, attackDuration, shakeIntensity))406 elif name == SHRED:407 camTrack.append(defaultCamera(openShotDuration=4.1))408 elif name == SPIN:409 camTrack.append(defaultCamera(openShotDuration=1.7))410 elif name == SYNERGY:411 camTrack.append(defaultCamera(openShotDuration=1.7))412 elif name == TABULATE:413 camTrack.append(defaultCamera())414 elif name == TEE_OFF:415 camTrack.append(defaultCamera(openShotDuration=4.5))416 elif name == TREMOR:417 shakeIntensity = 0.25418 camTrack.append(suitCameraShakeShot(suit, attackDuration, shakeIntensity))419 elif name == WATERCOOLER:420 camTrack.append(defaultCamera())421 elif name == WITHDRAWAL:422 camTrack.append(defaultCamera(openShotDuration=1.2))423 elif name == WRITE_OFF:424 camTrack.append(defaultCamera())425 else:426 notify.warning('unknown attack id in chooseSuitShot: %d using default cam' % name)427 camTrack.append(defaultCamera())428 pbpText = attack['playByPlayText']429 displayName = TTLocalizer.SuitAttackNames[attack['name']]430 pbpTrack = pbpText.getShowInterval(displayName, 3.5)431 return Parallel(camTrack, pbpTrack)432def chooseSuitCloseShot(attack, openDuration, openName, attackDuration):433 av = None434 duration = attackDuration - openDuration435 if duration < 0:436 duration = 1e-06437 groupStatus = attack['group']438 diedTrack = None439 if groupStatus == ATK_TGT_SINGLE:440 av = attack['target']['toon']441 shotChoices = [avatarCloseUpThreeQuarterRightShot, suitGroupThreeQuarterLeftBehindShot]442 died = attack['target']['died']443 if died != 0:444 pbpText = attack['playByPlayText']445 diedText = av.getName() + ' was defeated!'446 diedTextList = [diedText]447 diedTrack = pbpText.getToonsDiedInterval(diedTextList, duration)448 elif groupStatus == ATK_TGT_GROUP:449 av = None450 shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]451 deadToons = []452 targetDicts = attack['target']453 for targetDict in targetDicts:454 died = targetDict['died']455 if died != 0:456 deadToons.append(targetDict['toon'])457 if len(deadToons) > 0:458 pbpText = attack['playByPlayText']459 diedTextList = []460 for toon in deadToons:461 pbpText = attack['playByPlayText']462 diedTextList.append(toon.getName() + ' was defeated!')463 diedTrack = pbpText.getToonsDiedInterval(diedTextList, duration)464 else:465 notify.error('Bad groupStatus: %s' % groupStatus)466 track = apply(random.choice(shotChoices), [av, duration])467 if diedTrack == None:468 return track469 else:470 mtrack = Parallel(track, diedTrack)471 return mtrack472 return473def makeShot(x, y, z, h, p, r, duration, other = None, name = 'makeShot'):474 if other:475 return heldRelativeShot(other, x, y, z, h, p, r, duration, name)476 else:477 return heldShot(x, y, z, h, p, r, duration, name)478def focusShot(x, y, z, duration, target, other = None, splitFocusPoint = None, name = 'focusShot'):479 track = Sequence()480 if other:481 track.append(Func(camera.setPos, other, Point3(x, y, z)))482 else:483 track.append(Func(camera.setPos, Point3(x, y, z)))484 if splitFocusPoint:485 track.append(Func(focusCameraBetweenPoints, target, splitFocusPoint))486 else:487 track.append(Func(camera.lookAt, target))488 track.append(Wait(duration))489 return track490def moveShot(x, y, z, h, p, r, duration, other = None, name = 'moveShot'):491 return motionShot(x, y, z, h, p, r, duration, other, name)492def focusMoveShot(x, y, z, duration, target, other = None, name = 'focusMoveShot'):493 camera.setPos(Point3(x, y, z))494 camera.lookAt(target)495 hpr = camera.getHpr()496 return motionShot(x, y, z, hpr[0], hpr[1], hpr[2], duration, other, name)497def chooseSOSShot(av, duration):498 shotChoices = [avatarCloseUpThreeQuarterRightShot,499 avatarBehindShot,500 avatarBehindHighShot,501 suitGroupThreeQuarterLeftBehindShot]502 track = apply(random.choice(shotChoices), [av, duration])503 return track504def chooseRewardShot(av, duration, allowGroupShot = 1):505 def chooseRewardShotNow(av):506 if av.playingAnim == 'victory' or not allowGroupShot:507 shotChoices = [(0,508 8,509 av.getHeight() * 0.66,510 179,511 15,512 0), (5.2,513 5.45,514 av.getHeight() * 0.66,515 131.5,516 3.6,517 0)]518 shot = random.choice(shotChoices)519 camera.setPosHpr(av, *shot)520 else:521 camera.setPosHpr(10, 0, 10, 115, -30, 0)522 return Sequence(Func(chooseRewardShotNow, av), Wait(duration))523def heldShot(x, y, z, h, p, r, duration, name = 'heldShot'):524 track = Sequence(name=name)525 track.append(Func(camera.setPosHpr, x, y, z, h, p, r))526 track.append(Wait(duration))527 return track528def heldRelativeShot(other, x, y, z, h, p, r, duration, name = 'heldRelativeShot'):529 track = Sequence(name=name)530 track.append(Func(camera.setPosHpr, other, x, y, z, h, p, r))531 track.append(Wait(duration))532 return track533def motionShot(x, y, z, h, p, r, duration, other = None, name = 'motionShot'):534 if other:535 posTrack = LerpPosInterval(camera, duration, pos=Point3(x, y, z), other=other)536 hprTrack = LerpHprInterval(camera, duration, hpr=Point3(h, p, r), other=other)537 else:538 posTrack = LerpPosInterval(camera, duration, pos=Point3(x, y, z))539 hprTrack = LerpHprInterval(camera, duration, hpr=Point3(h, p, r))540 return Parallel(posTrack, hprTrack)541def allGroupShot(avatar, duration):542 return heldShot(10, 0, 10, 89, -30, 0, duration, 'allGroupShot')543def allGroupLowShot(avatar, duration):544 return heldShot(15, 0, 3, 89, 0, 0, duration, 'allGroupLowShot')545def allGroupLowDiagonalShot(avatar, duration):546 return heldShot(7, 5, 6, 119, -30, 0, duration, 'allGroupLowShot')547def toonGroupShot(avatar, duration):548 return heldShot(10, 0, 10, 115, -30, 0, duration, 'toonGroupShot')549def toonGroupHighShot(avatar, duration):550 return heldShot(5, 0, 1, 115, 45, 0, duration, 'toonGroupHighShot')551def suitGroupShot(avatar, duration):552 return heldShot(10, 0, 10, 65, -30, 0, duration, 'suitGroupShot')553def suitGroupLowLeftShot(avatar, duration):554 return heldShot(8.4, -3.85, 2.75, 36.3, 3.25, 0, duration, 'suitGroupLowLeftShot')555def suitGroupThreeQuarterLeftBehindShot(avatar, duration):556 if random.random() > 0.5:557 x = 12.37558 h = 134.61559 else:560 x = -12.37561 h = -134.61562 return heldShot(x, 11.5, 8.16, h, -22.7, 0, duration, 'suitGroupThreeQuarterLeftBehindShot')563def suitWakeUpShot(avatar, duration):564 return heldShot(10, -5, 10, 65, -30, 0, duration, 'suitWakeUpShot')565def suitCameraShakeShot(avatar, duration, shakeIntensity, quake = 0):566 track = Sequence(name='suitShakeCameraShot')567 if quake == 1:568 shakeDelay = 1.1569 numShakes = 4570 else:571 shakeDelay = 0.3572 numShakes = 5573 postShakeDelay = 0.5574 shakeTime = (duration - shakeDelay - postShakeDelay) / numShakes575 shakeDuration = shakeTime * (1.0 / numShakes)576 shakeWaitInterval = shakeTime * ((numShakes - 1.0) / numShakes)577 def shakeCameraTrack(intensity, shakeWaitInterval = shakeWaitInterval, quake = quake, shakeDuration = shakeDuration, numShakes = numShakes):578 vertShakeTrack = Sequence(Wait(shakeWaitInterval), Func(camera.setZ, camera.getZ() + intensity / 2), Wait(shakeDuration / 2), Func(camera.setZ, camera.getZ() - intensity), Wait(shakeDuration / 2), Func(camera.setZ, camera.getZ() + intensity / 2))579 horizShakeTrack = Sequence(Wait(shakeWaitInterval - shakeDuration / 2), Func(camera.setY, camera.getY() + intensity / 4), Wait(shakeDuration / 2), Func(camera.setY, camera.getY() - intensity / 2), Wait(shakeDuration / 2), Func(camera.setY, camera.getY() + intensity / 4), Wait(shakeDuration / 2), Func(camera.lookAt, Point3(0, 0, 0)))580 shakeTrack = Sequence()581 for i in xrange(0, numShakes):582 if quake == 0:583 shakeTrack.append(vertShakeTrack)584 else:585 shakeTrack.append(Parallel(vertShakeTrack, horizShakeTrack))586 return shakeTrack587 x = 10 + random.random() * 3588 if random.random() > 0.5:589 x = -x590 z = 7 + random.random() * 3591 track.append(Func(camera.setPos, x, -5, z))592 track.append(Func(camera.lookAt, Point3(0, 0, 0)))593 track.append(Wait(shakeDelay))594 track.append(shakeCameraTrack(shakeIntensity))595 track.append(Wait(postShakeDelay))596 return track597def avatarCloseUpShot(avatar, duration):598 return heldRelativeShot(avatar, 0, 8, avatar.getHeight() * 0.66, 179, 15, 0, duration, 'avatarCloseUpShot')599def avatarCloseUpThrowShot(avatar, duration):600 return heldRelativeShot(avatar, 3, 8, avatar.getHeight() * 0.66, 159, 3.6, 0, duration, 'avatarCloseUpThrowShot')601def avatarCloseUpThreeQuarterRightShot(avatar, duration):602 return heldRelativeShot(avatar, 5.2, 5.45, avatar.getHeight() * 0.66, 131.5, 3.6, 0, duration, 'avatarCloseUpThreeQuarterRightShot')603def avatarCloseUpThreeQuarterRightShotWide(avatar, duration):604 return heldRelativeShot(avatar, 7.2, 8.45, avatar.getHeight() * 0.66, 131.5, 3.6, 0, duration, 'avatarCloseUpThreeQuarterRightShot')605def avatarCloseUpThreeQuarterLeftShot(avatar, duration):606 return heldRelativeShot(avatar, -5.2, 5.45, avatar.getHeight() * 0.66, -131.5, 3.6, 0, duration, 'avatarCloseUpThreeQuarterLeftShot')607def avatarCloseUpThreeQuarterRightFollowShot(avatar, duration):608 track = Sequence(name='avatarCloseUpThreeQuarterRightFollowShot')609 track.append(heldRelativeShot(avatar, 5.2, 5.45, avatar.getHeight() * 0.66, 131.5, 3.6, 0, duration * 0.65))610 track.append(LerpHprInterval(nodePath=camera, other=avatar, duration=duration * 0.2, hpr=Point3(110, 3.6, 0), blendType='easeInOut'))611 track.append(Wait(duration * 0.25))612 return track613def avatarCloseUpZoomShot(avatar, duration):614 track = Sequence('avatarCloseUpZoomShot')615 track.append(LerpPosHprInterval(nodePath=camera, other=avatar, duration=duration / 2, startPos=Point3(0, 10, avatar.getHeight()), startHpr=Point3(179, -10, 0), pos=Point3(0, 6, avatar.getHeight()), hpr=Point3(179, -10, 0), blendType='easeInOut'))616 track.append(Wait(duration / 2))617 return track618def avatarBehindShot(avatar, duration):619 return heldRelativeShot(avatar, 5, -7, avatar.getHeight(), 40, -12, 0, duration, 'avatarBehindShot')620def avatarBehindHighShot(avatar, duration):621 return heldRelativeShot(avatar, -4, -7, 5 + avatar.getHeight(), -30, -35, 0, duration, 'avatarBehindHighShot')622def avatarBehindHighRightShot(avatar, duration):623 return heldRelativeShot(avatar, 4, -7, 5 + avatar.getHeight(), 30, -35, 0, duration, 'avatarBehindHighShot')624def avatarBehindThreeQuarterRightShot(avatar, duration):625 return heldRelativeShot(avatar, 7.67, -8.52, avatar.getHeight() * 0.66, 25, 7.5, 0, duration, 'avatarBehindThreeQuarterRightShot')626def avatarSideFollowAttack(suit, toon, duration, battle):627 windupDuration = duration * (0.1 + random.random() * 0.1)628 projectDuration = duration * 0.75629 impactDuration = duration - windupDuration - projectDuration630 suitHeight = suit.getHeight()631 toonHeight = toon.getHeight()632 suitCentralPoint = suit.getPos(battle)633 suitCentralPoint.setZ(suitCentralPoint.getZ() + suitHeight * 0.75)634 toonCentralPoint = toon.getPos(battle)635 toonCentralPoint.setZ(toonCentralPoint.getZ() + toonHeight * 0.75)636 initialX = random.randint(12, 14)637 finalX = random.randint(7, 8)638 initialY = finalY = random.randint(-3, 0)639 initialZ = suitHeight * 0.5 + random.random() * suitHeight640 finalZ = toonHeight * 0.5 + random.random() * toonHeight641 if random.random() > 0.5:642 initialX = -initialX643 finalX = -finalX644 return Sequence(focusShot(initialX, initialY, initialZ, windupDuration, suitCentralPoint), focusMoveShot(finalX, finalY, finalZ, projectDuration, toonCentralPoint), Wait(impactDuration))645def focusCameraBetweenPoints(point1, point2):646 if point1[0] > point2[0]:647 x = point2[0] + (point1[0] - point2[0]) * 0.5648 else:649 x = point1[0] + (point2[0] - point1[0]) * 0.5650 if point1[1] > point2[1]:651 y = point2[1] + (point1[1] - point2[1]) * 0.5652 else:653 y = point1[1] + (point2[1] - point1[1]) * 0.5654 if point1[2] > point2[2]:655 z = point2[2] + (point1[2] - point2[2]) * 0.5656 else:657 z = point1[2] + (point2[2] - point1[2]) * 0.5658 camera.lookAt(Point3(x, y, z))659def randomCamera(suit, toon, battle, attackDuration, openShotDuration):660 return randomAttackCam(suit, toon, battle, attackDuration, openShotDuration, 'suit')661def randomAttackCam(suit, toon, battle, attackDuration, openShotDuration, attackerString = 'suit'):662 if openShotDuration > attackDuration:663 openShotDuration = attackDuration664 closeShotDuration = attackDuration - openShotDuration665 if attackerString == 'suit':666 attacker = suit667 defender = toon668 defenderString = 'toon'669 else:670 attacker = toon671 defender = suit672 defenderString = 'suit'673 randomDouble = random.random()674 if randomDouble > 0.6:675 openShot = randomActorShot(attacker, battle, openShotDuration, attackerString)676 elif randomDouble > 0.2:677 openShot = randomOverShoulderShot(suit, toon, battle, openShotDuration, focus=attackerString)678 else:679 openShot = randomSplitShot(attacker, defender, battle, openShotDuration)680 randomDouble = random.random()681 if randomDouble > 0.6:682 closeShot = randomActorShot(defender, battle, closeShotDuration, defenderString)683 elif randomDouble > 0.2:684 closeShot = randomOverShoulderShot(suit, toon, battle, closeShotDuration, focus=defenderString)685 else:686 closeShot = randomSplitShot(attacker, defender, battle, closeShotDuration)687 return Sequence(openShot, closeShot)688def randomGroupAttackCam(suit, targets, battle, attackDuration, openShotDuration):689 if openShotDuration > attackDuration:690 openShotDuration = attackDuration691 closeShotDuration = attackDuration - openShotDuration692 openShot = randomActorShot(suit, battle, openShotDuration, 'suit', groupShot=0)693 closeShot = randomToonGroupShot(targets, suit, closeShotDuration, battle)694 return Sequence(openShot, closeShot)695def randomActorShot(actor, battle, duration, actorType, groupShot = 0):696 height = actor.getHeight()697 centralPoint = actor.getPos(battle)698 centralPoint.setZ(centralPoint.getZ() + height * 0.75)699 if actorType == 'suit':700 x = 4 + random.random() * 8701 y = -2 - random.random() * 4702 z = height * 0.5 + random.random() * height * 1.5703 if groupShot == 1:704 y = -4705 z = height * 0.5706 else:707 x = 2 + random.random() * 8708 y = -2 + random.random() * 3709 z = height + random.random() * height * 1.5710 if groupShot == 1:711 y = y + 3712 z = height * 0.5713 if MovieUtil.shotDirection == 'left':714 x = -x715 return focusShot(x, y, z, duration, centralPoint)716def randomSplitShot(suit, toon, battle, duration):717 suitHeight = suit.getHeight()718 toonHeight = toon.getHeight()719 suitCentralPoint = suit.getPos(battle)720 suitCentralPoint.setZ(suitCentralPoint.getZ() + suitHeight * 0.75)721 toonCentralPoint = toon.getPos(battle)722 toonCentralPoint.setZ(toonCentralPoint.getZ() + toonHeight * 0.75)723 x = 9 + random.random() * 2724 y = -2 - random.random() * 2725 z = suitHeight * 0.5 + random.random() * suitHeight726 if MovieUtil.shotDirection == 'left':727 x = -x728 return focusShot(x, y, z, duration, toonCentralPoint, splitFocusPoint=suitCentralPoint)729def randomOverShoulderShot(suit, toon, battle, duration, focus):730 suitHeight = suit.getHeight()731 toonHeight = toon.getHeight()732 suitCentralPoint = suit.getPos(battle)733 suitCentralPoint.setZ(suitCentralPoint.getZ() + suitHeight * 0.75)734 toonCentralPoint = toon.getPos(battle)735 toonCentralPoint.setZ(toonCentralPoint.getZ() + toonHeight * 0.75)736 x = 2 + random.random() * 10737 if focus == 'toon':738 y = 8 + random.random() * 6739 z = suitHeight * 1.2 + random.random() * suitHeight740 else:741 y = -10 - random.random() * 6742 z = toonHeight * 1.5743 if MovieUtil.shotDirection == 'left':744 x = -x745 return focusShot(x, y, z, duration, toonCentralPoint, splitFocusPoint=suitCentralPoint)746def randomCameraSelection(suit, attack, attackDuration, openShotDuration):747 shotChoices = [avatarCloseUpThrowShot,748 avatarCloseUpThreeQuarterLeftShot,749 allGroupLowShot,750 suitGroupLowLeftShot,751 avatarBehindHighShot]752 if openShotDuration > attackDuration:753 openShotDuration = attackDuration754 closeShotDuration = attackDuration - openShotDuration755 openShot = apply(random.choice(shotChoices), [suit, openShotDuration])756 closeShot = chooseSuitCloseShot(attack, closeShotDuration, openShot.getName(), attackDuration)757 return Sequence(openShot, closeShot)758def randomToonGroupShot(toons, suit, duration, battle):759 sum = 0760 for t in toons:761 toon = t['toon']762 height = toon.getHeight()763 sum = sum + height764 avgHeight = sum / len(toons) * 0.75765 suitPos = suit.getPos(battle)766 x = 1 + random.random() * 6767 if suitPos.getX() > 0:768 x = -x769 if random.random() > 0.5:770 y = 4 + random.random() * 1771 z = avgHeight + random.random() * 6772 else:773 y = 11 + random.random() * 2774 z = 13 + random.random() * 2775 focalPoint = Point3(0, -4, avgHeight)776 return focusShot(x, y, z, duration, focalPoint)777def chooseFireShot(throws, suitThrowsDict, attackDuration):778 openShot = chooseFireOpenShot(throws, suitThrowsDict, attackDuration)779 openDuration = openShot.getDuration()780 openName = openShot.getName()781 closeShot = chooseFireCloseShot(throws, suitThrowsDict, openDuration, openName, attackDuration)782 track = Sequence(openShot, closeShot)783 return track784def chooseFireOpenShot(throws, suitThrowsDict, attackDuration):785 numThrows = len(throws)786 av = None787 duration = 3.0788 if numThrows == 1:789 av = throws[0]['toon']790 shotChoices = [avatarCloseUpThrowShot,791 avatarCloseUpThreeQuarterRightShot,792 avatarBehindShot,793 allGroupLowShot,794 suitGroupThreeQuarterLeftBehindShot]795 elif numThrows >= 2 and numThrows <= 4:796 shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]797 else:798 notify.error('Bad number of throws: %s' % numThrows)799 shotChoice = random.choice(shotChoices)800 track = apply(shotChoice, [av, duration])801 print 'chooseFireOpenShot %s' % shotChoice802 return track803def chooseFireCloseShot(throws, suitThrowsDict, openDuration, openName, attackDuration):804 numSuits = len(suitThrowsDict)805 av = None806 duration = attackDuration - openDuration807 if numSuits == 1:808 av = base.cr.doId2do[suitThrowsDict.keys()[0]]809 shotChoices = [avatarCloseUpFireShot,810 avatarCloseUpThreeQuarterLeftFireShot,811 allGroupLowShot,812 suitGroupThreeQuarterLeftBehindShot]813 elif numSuits >= 2 and numSuits <= 4 or numSuits == 0:814 shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot]815 else:816 notify.error('Bad number of suits: %s' % numSuits)817 shotChoice = random.choice(shotChoices)818 track = apply(shotChoice, [av, duration])819 print 'chooseFireOpenShot %s' % shotChoice820 return track821def avatarCloseUpFireShot(avatar, duration):822 return heldRelativeShot(avatar, 7, 17, avatar.getHeight() * 0.66, 159, 3.6, 0, duration, 'avatarCloseUpFireShot')823def avatarCloseUpThreeQuarterLeftFireShot(avatar, duration):...
client.py
Source:client.py
1import random2import requests3from qclient import QClient4import lz4.frame5import lz4.block6import time7# client = QClient(node_list=('https://localhost:8888',), verify='../tls/ca.pem', cert='../tls/host.pem')8client = QClient(node_list=('http://localhost:8888',))9def generate_csv(byte_size):10 header = b'abc,def,ghi,jkl,mno\r\n'11 body = []12 l = len(header)13 row_count = 014 while True:15 row_count += 116 number = round(random.uniform(-1000, 1000), 2)17 line = f"foobar,,,{number},10"18 l += 2 + len(line)19 body.append(line)20 if l > byte_size:21 break22 data = "\r\n".join(body).encode("utf-8")23 return header + data, row_count24def post_data(data_type, headers, data, orig_size):25 t0 = time.time()26 client.post("test-key", data, content_type='text/csv', post_headers=headers)27 print("Post duration {} {}: {}".format(data_type, orig_size, time.time() - t0))28def get_data(data_type, headers, orig_size):29 t0 = time.time()30 resp = client.get("test-key", {}, query_headers=headers)31 print("Get duration {} {}: {}".format(data_type, orig_size, time.time() - t0))32 return resp33def block_compressed_benchmark(data, row_count):34 t0 = time.time()35 compressed_data = lz4.block.compress(data)36 size = len(data)37 print("Block compress duration {}: {}".format(size, time.time() - t0))38 post_headers = {'Content-Encoding': 'lz4', 'X-QCache-row-count-hint': str(row_count)}39 post_data("block-compressed", post_headers, compressed_data, size)40 resp = get_data("block-compressed", {"Accept-Encoding": "lz4"}, size)41 t0 = time.time()42 lz4.block.compress(resp.content)43 print("Block decompress duration {}: {}".format(len(resp.content), time.time() - t0))44 t0 = time.time()45 compressed_data = lz4.block.compress(data)46 print("Python block compress duration {}: {}".format(len(data), time.time() - t0))47 t0 = time.time()48 lz4.block.decompress(compressed_data)49 print("Python block decompress duration {}: {}".format(len(compressed_data), time.time() - t0))50def block_compressed_post_load(data):51 compressed_data = lz4.block.compress(data)52 size = len(data)53 post_headers = {'Content-Encoding': 'lz4'}54 while True:55 post_data("block-compressed-load", post_headers, compressed_data, size)56def block_compressed_get_load(data):57 compressed_data = lz4.block.compress(data)58 size = len(data)59 post_headers = {'Content-Encoding': 'lz4'}60 post_data("block-compressed-load", post_headers, compressed_data, size)61 while True:62 get_data("block-compressed", {"Accept-Encoding": "lz4"}, size)63def frame_compressed_benchmark(data):64 t0 = time.time()65 compressed_data = lz4.frame.compress(data, block_linked=False)66 size = len(data)67 print("Frame compress duration {}: {}".format(size, time.time() - t0))68 post_headers = {'Content-Encoding': 'lz4-frame'}69 post_data("frame-compressed", post_headers, compressed_data, size)70 resp = get_data("frame-compressed", {"Accept-Encoding": "lz4-frame"}, size)71 t0 = time.time()72 data = lz4.frame.decompress(resp.content)73 print("Frame decompress duration {}: {}".format(len(resp.content), time.time() - t0))74 t0 = time.time()75 compressed_data = lz4.frame.compress(data)76 print("Python frame compress duration {}: {}".format(size, time.time() - t0))77 t0 = time.time()78 lz4.frame.decompress(compressed_data)79 print("Python frame decompress duration {}: {}".format(len(compressed_data), time.time() - t0))80def uncompressed_benchmark(data, row_count):81 post_data("uncompressed", {"X-QCache-row-count-hint": str(row_count)}, data, len(data))82 get_data("uncompressed", {}, len(data))83def compress_decompress_benchmark(data):84 t0 = time.time()85 compressed_data = lz4.block.compress(data)86 print("Block compress duration: {}".format(time.time() - t0))87 t0 = time.time()88 lz4.block.decompress(compressed_data)89 print("Block decompress duration: {}".format(time.time() - t0))90 t0 = time.time()91 compressed_data = lz4.frame.compress(data, block_linked=False)92 print("Frame compress duration: {}".format(time.time() - t0))93 t0 = time.time()94 lz4.frame.decompress(compressed_data)95 print("Frame decompress duration {}: {}".format(len(data), time.time() - t0))96 t0 = time.time()97 compressed_data = lz4.frame.compress(data, block_linked=False, store_size=False)98 print("Frame compress no size duration: {}".format(time.time() - t0))99 t0 = time.time()100 lz4.frame.decompress(compressed_data)101 print("Frame decompress no size duration {}: {}".format(len(data), time.time() - t0))102def requests_performance():103 # s = requests.Session()104 s = requests.Session()105 s.verify = '../tls/ca.pem'106 s.cert = '../tls/host.pem'107 # Setting this to false cuts requests overhead from 9-10 ms to 2 - 4 ms.108 s.trust_env = False109 for _ in range(100):110 t0 = time.time()111 resp = s.get("https://localhost:8888/qcache/status")112 print("Duration: {}".format(time.time() - t0))113 assert resp.status_code == 200114if False:115 requests_performance()116if True:117 sizes = (1000, 100000, 10000000)118 for s in sizes:119 print(f"\n----- {s} -----")120 csv_data, row_count = generate_csv(s)121 block_compressed_benchmark(csv_data, row_count)122 # frame_compressed_benchmark(csv_data)123 uncompressed_benchmark(csv_data, row_count)124 # compress_decompress_benchmark(csv_data)125if False:126 csv_data = generate_csv(1000)127 block_compressed_benchmark(csv_data)128if False:129 csv_data = generate_csv(10000)130 block_compressed_get_load(csv_data)131# ----- 1000 -----132# Block compress duration 1016: 3.4809112548828125e-05133# Post duration block-compressed 1016: 0.010013580322265625134# Get duration block-compressed 1016: 0.006348133087158203135# Block decompress duration 502: 1.430511474609375e-05136# Python block compress duration 1016: 1.7404556274414062e-05137# Python block decompress duration 423: 6.4373016357421875e-06138# Frame compress duration 1016: 2.574920654296875e-05139# Post duration frame-compressed 1016: 0.005291938781738281140# Get duration frame-compressed 1016: 0.00875997543334961141# Frame decompress duration 515: 0.0002288818359375142# Python frame compress duration 1016: 2.8371810913085938e-05143# Python frame decompress duration 514: 3.647804260253906e-05144# Post duration uncompressed 1016: 0.006818056106567383145# Get duration uncompressed 1016: 0.00618290901184082146# Block compress duration: 1.9550323486328125e-05147# Block decompress duration: 6.4373016357421875e-06148# Frame compress duration: 2.5033950805664062e-05149# Frame decompress duration 1016: 2.3365020751953125e-05150# Frame compress no size duration: 1.9788742065429688e-05151# Frame decompress no size duration 1016: 1.5735626220703125e-05152#153# ----- 100000 -----154# Block compress duration 99999: 0.0007016658782958984155# Post duration block-compressed 99999: 0.013032197952270508156# Get duration block-compressed 99999: 0.014141321182250977157# Block decompress duration 35022: 0.0008203983306884766158# Python block compress duration 99999: 0.0007052421569824219159# Python block decompress duration 28511: 0.00023317337036132812160# Frame compress duration 99999: 0.0005924701690673828161# Post duration frame-compressed 99999: 0.019430875778198242162# Get duration frame-compressed 99999: 0.024871110916137695163# Frame decompress duration 35032: 0.00883936882019043164# Python frame compress duration 99999: 0.0008690357208251953165# Python frame decompress duration 33211: 0.0006248950958251953166# Post duration uncompressed 99999: 0.01810288429260254167# Get duration uncompressed 99999: 0.018460750579833984168# Block compress duration: 0.0007646083831787109169# Block decompress duration: 0.00015592575073242188170# Frame compress duration: 0.0006260871887207031171# Frame decompress duration 99999: 0.0001850128173828125172# Frame compress no size duration: 0.00054931640625173# Frame decompress no size duration 99999: 0.0014286041259765625174#175# ----- 10000000 -----176# Block compress duration 10000015: 0.07544541358947754177# Post duration block-compressed 10000015: 0.6772036552429199178# Get duration block-compressed 10000015: 0.8411071300506592179# Block decompress duration 3473944: 0.09713077545166016180# Python block compress duration 10000015: 0.07901954650878906181# Python block decompress duration 2797066: 0.02633380889892578182# Frame compress duration 10000015: 0.06122398376464844183# Post duration frame-compressed 10000015: 0.701441764831543184# Get duration frame-compressed 10000015: 0.7850394248962402185# Frame decompress duration 3475857: 0.7355217933654785186# Python frame compress duration 10000015: 0.0748136043548584187# Python frame decompress duration 3275922: 0.06526613235473633188# Post duration uncompressed 10000015: 0.647383451461792189# Get duration uncompressed 10000015: 1.1222872734069824190# Block compress duration: 0.07514023780822754191# Block decompress duration: 0.016193151473999023192# Frame compress duration: 0.05902743339538574193# Frame decompress duration 10000015: 0.01868605613708496194# Frame compress no size duration: 0.05801844596862793195# Frame decompress no size duration 10000015: 0.14292049407958984196# QCache, for reference197# ----- 1000 -----198# Block compress duration 1000: 1.4066696166992188e-05199# Post duration block-compressed 1000: 0.018204689025878906200# Get duration block-compressed 1000: 0.024323463439941406201# Block decompress duration 491: 2.002716064453125e-05202# Python block compress duration 1000: 1.7881393432617188e-05203# Python block decompress duration 417: 7.867813110351562e-06204# Post duration uncompressed 1000: 0.01737213134765625205# Get duration uncompressed 1000: 0.04035592079162598206#207# ----- 100000 -----208# Block compress duration 100014: 0.0005407333374023438209# Post duration block-compressed 100014: 0.03321433067321777210# Get duration block-compressed 100014: 0.037641286849975586211# Block decompress duration 33103: 0.0006084442138671875212# Python block compress duration 100014: 0.0004901885986328125213# Python block decompress duration 28478: 0.0002918243408203125214# Post duration uncompressed 100014: 0.028759241104125977215# Get duration uncompressed 100014: 0.049143314361572266216#217# ----- 10000000 -----218# Block compress duration 10000018: 0.05651998519897461219# Post duration block-compressed 10000018: 1.061251163482666220# Get duration block-compressed 10000018: 2.4552574157714844221# Block decompress duration 3273599: 0.05962109565734863222# Python block compress duration 10000018: 0.05662846565246582223# Python block decompress duration 2796747: 0.027180910110473633224# Post duration uncompressed 10000018: 1.0426273345947266...
template.tpl
Source:template.tpl
1#!/usr/bin/env python32from goalee import Target, RedisMiddleware3from goalee.topic_goals import TopicMessageReceivedGoal, TopicMessageParamGoal4from goalee.area_goals import RectangleAreaGoal, CircularAreaGoal5from goalee.complex_goal import ComplexGoal, ComplexGoalAlgorithm6from goalee.types import Point7if __name__ == '__main__':8 {% if middleware.__class__.__name__ == 'AMQPBroker' %}9 middleware = AMQPMiddleware()10 {% elif middleware.__class__.__name__ == 'RedisBroker' %}11 middleware = RedisMiddleware()12 {% endif %}13 t = Target(middleware, name='{{ target.name }}',14 score_weights={{ target.scoreWeights }})15 {% for goal in target.goals %}16 {% if goal.__class__.__name__ == 'TopicMessageReceivedGoal' %}17 g = TopicMessageReceivedGoal(topic='{{ goal.topic }}',18 name='{{ goal.name }}',19 max_duration={{ goal.max_duration }},20 min_duration={{ goal.min_duration }})21 {% elif goal.__class__.__name__ == 'TopicMessageParamGoal' %}22 g = TopicMessageParamGoal(topic='{{ goal.topic }}',23 name='{{ goal.name }}',24 condition={{ goal.cond_lambda }},25 max_duration={{ goal.max_duration }},26 min_duration={{ goal.min_duration }})27 {% elif goal.__class__.__name__ == 'CircularAreaGoal' %}28 g = CircularAreaGoal(topic='{{ goal.topic }}',29 name='{{ goal.name }}',30 center=Point({{ goal.center.x }}, {{ goal.center.y }}),31 radius={{ goal.radius }},32 max_duration={{ goal.max_duration }},33 min_duration={{ goal.min_duration }})34 {% elif goal.__class__.__name__ == 'RectangleAreaGoal' %}35 g = RectangleAreaGoal(topic='{{ goal.topic }}',36 name='{{ goal.name }}',37 bottom_left_edge=Point({{ goal.bottomLeftEdge.x }}, {{ goal.bottomLeftEdge.y }}),38 length_x={{ goal.lengthX }},39 length_y={{ goal.lengthY }},40 max_duration={{ goal.max_duration }},41 min_duration={{ goal.min_duration }})42 {% elif goal.__class__.__name__ == 'ComplexGoal' %}43 g = ComplexGoal(name='{{ goal.name }}',44 {% if goal.algorithm.__class__.__name__ == 'ALL_ACCOMPLISHED'%}45 algorithm=ComplexGoalAlgorithm.ALL_ACCOMPLISHED,46 {% elif goal.algorithm.__class__.__name__ == 'NONE_ACCOMPLISHED'%}47 algorithm=ComplexGoalAlgorithm.NONE_ACCOMPLISHED,48 {% endif %}49 max_duration={{ goal.max_duration }},50 min_duration={{ goal.min_duration }})51 {% for goal in goal.goals %}52 {% if goal.__class__.__name__ == 'TopicMessageReceivedGoal' %}53 gs = TopicMessageReceivedGoal(topic='{{ goal.topic }}',54 name='{{ goal.name }}',55 max_duration={{ goal.max_duration }},56 min_duration={{ goal.min_duration }})57 {% elif goal.__class__.__name__ == 'TopicMessageParamGoal' %}58 gs = TopicMessageParamGoal(topic='{{ goal.topic }}',59 name='{{ goal.name }}',60 condition={{ goal.cond_lambda }},61 max_duration={{ goal.max_duration }},62 min_duration={{ goal.min_duration }})63 {% elif goal.__class__.__name__ == 'CircularAreaGoal' %}64 gs = CircularAreaGoal(topic='{{ goal.topic }}',65 name='{{ goal.name }}',66 center=Point({{ goal.center.x }}, {{ goal.center.y }}),67 radius={{ goal.radius }},68 max_duration={{ goal.max_duration }},69 min_duration={{ goal.min_duration }})70 {% elif goal.__class__.__name__ == 'RectangleAreaGoal' %}71 gs = RectangleAreaGoal(topic='{{ goal.topic }}',72 name='{{ goal.name }}',73 bottom_left_edge=Point({{ goal.bottomLeftEdge.x }}, {{ goal.bottomLeftEdge.y }}),74 length_x={{ goal.lengthX }},75 length_y={{ goal.lengthY }},76 max_duration={{ goal.max_duration }},77 min_duration={{ goal.min_duration }})78 {% endif %}79 g.add_goal(gs)80 {% endfor %}81 ## More Goals to Generate here82 {% endif %}83 t.add_goal(g)84 {% endfor %}85 {% if target.concurrent == True %}86 t.run_concurrent()87 {% else %}88 t.run_seq()...
test_duration.py
Source:test_duration.py
...19 self.assertEqual(duration_string(duration), '-1 01:03:05')20class TestParseDurationRoundtrip(unittest.TestCase):21 def test_simple(self):22 duration = datetime.timedelta(hours=1, minutes=3, seconds=5)23 self.assertEqual(parse_duration(duration_string(duration)), duration)24 def test_days(self):25 duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5)26 self.assertEqual(parse_duration(duration_string(duration)), duration)27 def test_microseconds(self):28 duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345)29 self.assertEqual(parse_duration(duration_string(duration)), duration)30 def test_negative(self):31 duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5)32 self.assertEqual(parse_duration(duration_string(duration)), duration)33class TestISODurationString(unittest.TestCase):34 def test_simple(self):35 duration = datetime.timedelta(hours=1, minutes=3, seconds=5)36 self.assertEqual(duration_iso_string(duration), 'P0DT01H03M05S')37 def test_days(self):38 duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5)39 self.assertEqual(duration_iso_string(duration), 'P1DT01H03M05S')40 def test_microseconds(self):41 duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345)42 self.assertEqual(duration_iso_string(duration), 'P0DT01H03M05.012345S')43 def test_negative(self):44 duration = -1 * datetime.timedelta(days=1, hours=1, minutes=3, seconds=5)45 self.assertEqual(duration_iso_string(duration), '-P1DT01H03M05S')46class TestParseISODurationRoundtrip(unittest.TestCase):47 def test_simple(self):48 duration = datetime.timedelta(hours=1, minutes=3, seconds=5)49 self.assertEqual(parse_duration(duration_iso_string(duration)), duration)50 def test_days(self):51 duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5)52 self.assertEqual(parse_duration(duration_iso_string(duration)), duration)53 def test_microseconds(self):54 duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345)55 self.assertEqual(parse_duration(duration_iso_string(duration)), duration)56 def test_negative(self):57 duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5)58 self.assertEqual(parse_duration(duration_iso_string(duration)).total_seconds(), duration.total_seconds())59class TestDurationMicroseconds(unittest.TestCase):60 def test(self):61 deltas = [62 datetime.timedelta.max,63 datetime.timedelta.min,64 datetime.timedelta.resolution,65 -datetime.timedelta.resolution,66 datetime.timedelta(microseconds=8999999999999999),67 ]68 for delta in deltas:69 with self.subTest(delta=delta):...
Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2var device = client.getDevice('1234567890');3device.duration(2000).then(function(){4 console.log('duration set to 2000 seconds');5});6stf.connect(url)7client.getDevice(serial)8device.isAvailable()9device.isReserved()10device.isUsed()11device.isBroken()12device.isOffline()13device.isOnline()14device.isIdle()15device.isIdleTimeout()16device.isIdleDisabled()17device.isIdleUnplug()18device.isScreenOn()19device.isScreenOff()20device.isScreenLocked()21device.isScreenUnlocked()22device.isCharging()23device.isNotCharging()24device.isAirplaneModeOn()25device.isAirplaneModeOff()26device.isRecovery()27device.isRecovery()28device.isBootloader()29device.isBootloader()30device.isDisplayOn()31device.isDisplayOff()32device.isDisplayUnlocked()33device.isDisplayLocked()34device.isDisplayOff()35device.isDisplayOff()
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!