Best Python code snippet using autotest_python
optionals.js
Source:optionals.js
...13 parser = new ArgumentParser({ debug: true });14 parser.addArgument([ '-x' ], { type: 'float' });15 parser.addArgument([ '-3' ], { dest: 'y', type: 'float' });16 parser.addArgument([ 'z' ], { nargs: '*' });17 args = parser.parseArgs([]);18 assert.deepEqual(args, { y: null, x: null, z: [] });19 args = parser.parseArgs([ '-x', '2.5' ]);20 assert.deepEqual(args, { y: null, x: 2.5, z: [] });21 args = parser.parseArgs([ '-x', '2.5', 'a' ]);22 assert.deepEqual(args, { y: null, x: 2.5, z: [ 'a' ] });23 args = parser.parseArgs([ '-3.5' ]);24 assert.deepEqual(args, { y: 0.5, x: null, z: [] });25 args = parser.parseArgs([ '-3-.5' ]);26 assert.deepEqual(args, { y: -0.5, x: null, z: [] });27 args = parser.parseArgs([ '-3', '.5' ]);28 assert.deepEqual(args, { y: 0.5, x: null, z: [] });29 args = parser.parseArgs([ 'a', '-3.5' ]);30 assert.deepEqual(args, { y: 0.5, x: null, z: [ 'a' ] });31 args = parser.parseArgs([ 'a' ]);32 assert.deepEqual(args, { y: null, x: null, z: [ 'a' ] });33 args = parser.parseArgs([ 'a', '-x', '1' ]);34 assert.deepEqual(args, { y: null, x: 1, z: [ 'a' ] });35 args = parser.parseArgs([ '-x', '1', 'a' ]);36 assert.deepEqual(args, { y: null, x: 1, z: [ 'a' ] });37 args = parser.parseArgs([ '-3', '1', 'a' ]);38 assert.deepEqual(args, { y: 1, x: null, z: [ 'a' ] });39 assert.throws(function () {40 args = parser.parseArgs([ '-x' ]);41 });42 assert.throws(function () {43 args = parser.parseArgs([ '-y2.5' ]);44 });45 assert.throws(function () {46 args = parser.parseArgs([ '-xa' ]);47 });48 assert.throws(function () {49 args = parser.parseArgs([ '-x', '-a' ]);50 });51 assert.throws(function () {52 args = parser.parseArgs([ '-x', '-3' ]);53 });54 assert.throws(function () {55 args = parser.parseArgs([ '-x', '-3.5' ]);56 });57 assert.throws(function () {58 args = parser.parseArgs([ '-3', '-3.5' ]);59 });60 assert.throws(function () {61 args = parser.parseArgs([ '-x', '-2.5' ]);62 });63 assert.throws(function () {64 args = parser.parseArgs([ '-x', '-2.5', 'a' ]);65 });66 assert.throws(function () {67 args = parser.parseArgs([ '-3', '-.5' ]);68 });69 assert.throws(function () {70 args = parser.parseArgs([ 'a', 'x', '-1' ]);71 });72 assert.throws(function () {73 args = parser.parseArgs([ '-x', '-1', 'a' ]);74 });75 assert.throws(function () {76 args = parser.parseArgs([ '-3', '-1', 'a' ]);77 });78 });79 it('test the append action for an Optional', function () {80 parser = new ArgumentParser({ debug: true });81 parser.addArgument([ '--baz' ], { action: 'append' });82 args = parser.parseArgs([]);83 assert.deepEqual(args, { baz: null });84 args = parser.parseArgs([ '--baz', 'a' ]);85 assert.deepEqual(args, { baz: [ 'a' ] });86 args = parser.parseArgs([ '--baz', 'a', '--baz', 'b' ]);87 assert.deepEqual(args, { baz: [ 'a', 'b' ] });88 assert.throws(function () {89 args = parser.parseArgs([ 'a' ]);90 });91 assert.throws(function () {92 args = parser.parseArgs([ '--baz' ]);93 });94 assert.throws(function () {95 args = parser.parseArgs([ 'a', '--baz' ]);96 });97 assert.throws(function () {98 args = parser.parseArgs([ '--baz', 'a', 'b' ]);99 });100 });101 it('test the append_const action for an Optional', function () {102 parser = new ArgumentParser({ debug: true });103 parser.addArgument([ '-b' ], { action: 'appendConst',104 const: 'Exception',105 constant: 'Exception' });106 parser.addArgument([ '-c' ], { dest: 'b', action: 'append' });107 args = parser.parseArgs([]);108 assert.deepEqual(args, { b: null });109 args = parser.parseArgs([ '-b' ]);110 assert.deepEqual(args, { b: [ 'Exception' ] });111 args = parser.parseArgs([ '-b', '-cx', '-b', '-cyz' ]);112 assert.deepEqual(args, { b: [ 'Exception', 'x', 'Exception', 'yz' ] });113 assert.throws(function () {114 args = parser.parseArgs([ 'a' ]);115 });116 assert.throws(function () {117 args = parser.parseArgs([ '-c' ]);118 });119 assert.throws(function () {120 args = parser.parseArgs([ 'a', '-c' ]);121 });122 assert.throws(function () {123 args = parser.parseArgs([ '-bx' ]);124 });125 assert.throws(function () {126 args = parser.parseArgs([ '-b', 'x' ]);127 });128 });129 it('test the append_const action for an Optional', function () {130 parser = new ArgumentParser({ debug: true });131 parser.addArgument([ '-b' ], { default: [ 'X' ],132 action: 'appendConst',133 const: 'Exception',134 defaultValue: [ 'X' ],135 constant: 'Exception' });136 parser.addArgument([ '-c' ], { dest: 'b', action: 'append' });137 args = parser.parseArgs([]);138 assert.deepEqual(args, { b: [ 'X' ] });139 args = parser.parseArgs([ '-b' ]);140 assert.deepEqual(args, { b: [ 'X', 'Exception' ] });141 args = parser.parseArgs([ '-b', '-cx', '-b', '-cyz' ]);142 assert.deepEqual(args, { b: [ 'X', 'Exception', 'x', 'Exception', 'yz' ] });143 assert.throws(function () {144 args = parser.parseArgs([ 'a' ]);145 });146 assert.throws(function () {147 args = parser.parseArgs([ '-c' ]);148 });149 assert.throws(function () {150 args = parser.parseArgs([ 'a', '-c' ]);151 });152 assert.throws(function () {153 args = parser.parseArgs([ '-bx' ]);154 });155 assert.throws(function () {156 args = parser.parseArgs([ '-b', 'x' ]);157 });158 });159 it('test the append action for an Optional', function () {160 parser = new ArgumentParser({ debug: true });161 parser.addArgument(162 [ '--baz' ],163 { default: [ 'X' ], action: 'append', defaultValue: [ 'X' ] }164 );165 args = parser.parseArgs([]);166 assert.deepEqual(args, { baz: [ 'X' ] });167 args = parser.parseArgs([ '--baz', 'a' ]);168 assert.deepEqual(args, { baz: [ 'X', 'a' ] });169 args = parser.parseArgs([ '--baz', 'a', '--baz', 'b' ]);170 assert.deepEqual(args, { baz: [ 'X', 'a', 'b' ] });171 assert.throws(function () {172 args = parser.parseArgs([ 'a' ]);173 });174 assert.throws(function () {175 args = parser.parseArgs([ '--baz' ]);176 });177 assert.throws(function () {178 args = parser.parseArgs([ 'a', '--baz' ]);179 });180 assert.throws(function () {181 args = parser.parseArgs([ '--baz', 'a', 'b' ]);182 });183 });184 it('test the count action for an Optional', function () {185 parser = new ArgumentParser({ debug: true });186 parser.addArgument([ '-x' ], { action: 'count' });187 args = parser.parseArgs([]);188 assert.deepEqual(args, { x: null });189 args = parser.parseArgs([ '-x' ]);190 assert.deepEqual(args, { x: 1 });191 assert.throws(function () {192 args = parser.parseArgs([ 'a' ]);193 });194 assert.throws(function () {195 args = parser.parseArgs([ '-x', 'a' ]);196 });197 assert.throws(function () {198 args = parser.parseArgs([ '-x', 'b' ]);199 });200 assert.throws(function () {201 args = parser.parseArgs([ '-x', 'a', '-x', 'b' ]);202 });203 });204 it('test the store action for an Optional', function () {205 parser = new ArgumentParser({ debug: true });206 parser.addArgument([ '-x' ], { action: 'store' });207 args = parser.parseArgs([]);208 assert.deepEqual(args, { x: null });209 args = parser.parseArgs([ '-xfoo' ]);210 assert.deepEqual(args, { x: 'foo' });211 assert.throws(function () {212 args = parser.parseArgs([ 'a' ]);213 });214 assert.throws(function () {215 args = parser.parseArgs([ 'a', '-x' ]);216 });217 });218 it('test the store_const action for an Optional', function () {219 parser = new ArgumentParser({ debug: true });220 parser.addArgument(221 [ '-y' ],222 { action: 'storeConst', const: 'object', constant: 'object' }223 );224 args = parser.parseArgs([]);225 assert.deepEqual(args, { y: null });226 args = parser.parseArgs([ '-y' ]);227 assert.deepEqual(args, { y: 'object' });228 assert.throws(function () {229 args = parser.parseArgs([ 'a' ]);230 });231 });232 it('test the store_false action for an Optional', function () {233 parser = new ArgumentParser({ debug: true });234 parser.addArgument([ '-z' ], { action: 'storeFalse' });235 args = parser.parseArgs([]);236 assert.deepEqual(args, { z: true });237 args = parser.parseArgs([ '-z' ]);238 assert.deepEqual(args, { z: false });239 assert.throws(function () {240 args = parser.parseArgs([ 'a' ]);241 });242 assert.throws(function () {243 args = parser.parseArgs([ '-za' ]);244 });245 assert.throws(function () {246 args = parser.parseArgs([ '-z', 'a' ]);247 });248 });249 it('test the store_true action for an Optional', function () {250 parser = new ArgumentParser({ debug: true });251 parser.addArgument([ '--apple' ], { action: 'storeTrue' });252 args = parser.parseArgs([]);253 assert.deepEqual(args, { apple: false });254 args = parser.parseArgs([ '--apple' ]);255 assert.deepEqual(args, { apple: true });256 assert.throws(function () {257 args = parser.parseArgs([ 'a' ]);258 });259 assert.throws(function () {260 args = parser.parseArgs([ '--apple=b' ]);261 });262 assert.throws(function () {263 args = parser.parseArgs([ '--apple', 'b' ]);264 });265 });266 it('test negative number args when almost numeric options are present', function () {267 parser = new ArgumentParser({ debug: true });268 parser.addArgument([ 'x' ], { nargs: '?' });269 parser.addArgument([ '-k4' ], { action: 'storeTrue', dest: 'y' });270 args = parser.parseArgs([]);271 assert.deepEqual(args, { y: false, x: null });272 args = parser.parseArgs([ '-2' ]);273 assert.deepEqual(args, { y: false, x: '-2' });274 args = parser.parseArgs([ 'a' ]);275 assert.deepEqual(args, { y: false, x: 'a' });276 args = parser.parseArgs([ '-k4' ]);277 assert.deepEqual(args, { y: true, x: null });278 args = parser.parseArgs([ '-k4', 'a' ]);279 assert.deepEqual(args, { y: true, x: 'a' });280 assert.throws(function () {281 args = parser.parseArgs([ '-k3' ]);282 });283 });284 it('test specifying the choices for an Optional', function () {285 parser = new ArgumentParser({ debug: true });286 parser.addArgument([ '-f' ], { choices: 'abc' });287 parser.addArgument([ '-g' ], { type: 'int', choices: [ 0, 1, 2, 3, 4 ] });288 args = parser.parseArgs([]);289 assert.deepEqual(args, { g: null, f: null });290 args = parser.parseArgs([ '-f', 'a' ]);291 assert.deepEqual(args, { g: null, f: 'a' });292 args = parser.parseArgs([ '-f', 'c' ]);293 assert.deepEqual(args, { g: null, f: 'c' });294 args = parser.parseArgs([ '-g', '0' ]);295 assert.deepEqual(args, { g: 0, f: null });296 args = parser.parseArgs([ '-g', '03' ]);297 assert.deepEqual(args, { g: 3, f: null });298 args = parser.parseArgs([ '-fb', '-g4' ]);299 assert.deepEqual(args, { g: 4, f: 'b' });300 assert.throws(function () {301 args = parser.parseArgs([ 'a' ]);302 });303 assert.throws(function () {304 args = parser.parseArgs([ '-f', 'd' ]);305 });306 assert.throws(function () {307 args = parser.parseArgs([ '-fad' ]);308 });309 assert.throws(function () {310 args = parser.parseArgs([ '-ga' ]);311 });312 assert.throws(function () {313 args = parser.parseArgs([ '-g', '6' ]);314 });315 });316 it('test specifying a default for an Optional', function () {317 parser = new ArgumentParser({ debug: true });318 parser.addArgument([ '-x' ], {});319 parser.addArgument([ '-y' ], { default: 42, defaultValue: 42 });320 args = parser.parseArgs([]);321 assert.deepEqual(args, { y: 42, x: null });322 args = parser.parseArgs([ '-xx' ]);323 assert.deepEqual(args, { y: 42, x: 'x' });324 args = parser.parseArgs([ '-yy' ]);325 assert.deepEqual(args, { y: 'y', x: null });326 assert.throws(function () {327 args = parser.parseArgs([ 'a' ]);328 });329 });330 it('test various means of setting destination', function () {331 parser = new ArgumentParser({ debug: true });332 parser.addArgument([ '--foo-bar' ], {});333 parser.addArgument([ '--baz' ], { dest: 'zabbaz' });334 args = parser.parseArgs([ '--foo-bar', 'f' ]);335 assert.deepEqual(args, { zabbaz: null, foo_bar: 'f' });336 args = parser.parseArgs([ '--baz', 'g' ]);337 assert.deepEqual(args, { zabbaz: 'g', foo_bar: null });338 args = parser.parseArgs([ '--foo-bar', 'h', '--baz', 'i' ]);339 assert.deepEqual(args, { zabbaz: 'i', foo_bar: 'h' });340 args = parser.parseArgs([ '--baz', 'j', '--foo-bar', 'k' ]);341 assert.deepEqual(args, { zabbaz: 'j', foo_bar: 'k' });342 assert.throws(function () {343 args = parser.parseArgs([ 'a' ]);344 });345 });346 it('test an Optional with a double-dash option string', function () {347 parser = new ArgumentParser({ debug: true });348 parser.addArgument([ '--foo' ], {});349 args = parser.parseArgs([]);350 assert.deepEqual(args, { foo: null });351 args = parser.parseArgs([ '--foo', 'a' ]);352 assert.deepEqual(args, { foo: 'a' });353 args = parser.parseArgs([ '--foo=a' ]);354 assert.deepEqual(args, { foo: 'a' });355 args = parser.parseArgs([ '--foo', '-2.5' ]);356 assert.deepEqual(args, { foo: '-2.5' });357 args = parser.parseArgs([ '--foo=-2.5' ]);358 assert.deepEqual(args, { foo: '-2.5' });359 assert.throws(function () {360 args = parser.parseArgs([ '--foo' ]);361 });362 assert.throws(function () {363 args = parser.parseArgs([ '-f' ]);364 });365 assert.throws(function () {366 args = parser.parseArgs([ '-f', 'a' ]);367 });368 assert.throws(function () {369 args = parser.parseArgs([ 'a' ]);370 });371 assert.throws(function () {372 args = parser.parseArgs([ '--foo', '-x' ]);373 });374 assert.throws(function () {375 args = parser.parseArgs([ '--foo', '--bar' ]);376 });377 });378 it('tests partial matching with a double-dash option string', function () {379 parser = new ArgumentParser({ debug: true });380 parser.addArgument([ '--badger' ], { action: 'storeTrue' });381 parser.addArgument([ '--bat' ], {});382 args = parser.parseArgs([]);383 assert.deepEqual(args, { bat: null, badger: false });384 args = parser.parseArgs([ '--bat', 'X' ]);385 assert.deepEqual(args, { bat: 'X', badger: false });386 args = parser.parseArgs([ '--bad' ]);387 assert.deepEqual(args, { bat: null, badger: true });388 args = parser.parseArgs([ '--badg' ]);389 assert.deepEqual(args, { bat: null, badger: true });390 args = parser.parseArgs([ '--badge' ]);391 assert.deepEqual(args, { bat: null, badger: true });392 args = parser.parseArgs([ '--badger' ]);393 assert.deepEqual(args, { bat: null, badger: true });394 assert.throws(function () {395 args = parser.parseArgs([ '--bar' ]);396 });397 assert.throws(function () {398 args = parser.parseArgs([ '--b' ]);399 });400 assert.throws(function () {401 args = parser.parseArgs([ '--ba' ]);402 });403 assert.throws(function () {404 args = parser.parseArgs([ '--b=2' ]);405 });406 assert.throws(function () {407 args = parser.parseArgs([ '--ba=4' ]);408 });409 assert.throws(function () {410 args = parser.parseArgs([ '--badge', '5' ]);411 });412 });413 it('test an Optional with a short opt string', function () {414 parser = new ArgumentParser({ debug: true });415 parser.addArgument([ '-1' ], { dest: 'one' });416 args = parser.parseArgs([]);417 assert.deepEqual(args, { one: null });418 args = parser.parseArgs([ '-1', 'a' ]);419 assert.deepEqual(args, { one: 'a' });420 args = parser.parseArgs([ '-1a' ]);421 assert.deepEqual(args, { one: 'a' });422 args = parser.parseArgs([ '-1-2' ]);423 assert.deepEqual(args, { one: '-2' });424 assert.throws(function () {425 args = parser.parseArgs([ '-1' ]);426 });427 assert.throws(function () {428 args = parser.parseArgs([ 'a' ]);429 });430 assert.throws(function () {431 args = parser.parseArgs([ '-1', '--foo' ]);432 });433 assert.throws(function () {434 args = parser.parseArgs([ '-1', '-y' ]);435 });436 assert.throws(function () {437 args = parser.parseArgs([ '-1', '-1' ]);438 });439 assert.throws(function () {440 args = parser.parseArgs([ '-1', '-2' ]);441 });442 });443 it('test negative number args when numeric options are present', function () {444 parser = new ArgumentParser({ debug: true });445 parser.addArgument([ 'x' ], { nargs: '?' });446 parser.addArgument([ '-4' ], { action: 'storeTrue', dest: 'y' });447 args = parser.parseArgs([]);448 assert.deepEqual(args, { y: false, x: null });449 args = parser.parseArgs([ 'a' ]);450 assert.deepEqual(args, { y: false, x: 'a' });451 args = parser.parseArgs([ '-4' ]);452 assert.deepEqual(args, { y: true, x: null });453 args = parser.parseArgs([ '-4', 'a' ]);454 assert.deepEqual(args, { y: true, x: 'a' });455 assert.throws(function () {456 args = parser.parseArgs([ '-2' ]);457 });458 assert.throws(function () {459 args = parser.parseArgs([ '-315' ]);460 });461 });462 it('tests the an optional action that is required', function () {463 parser = new ArgumentParser({ debug: true });464 parser.addArgument([ '-x' ], { required: true, type: 'int' });465 args = parser.parseArgs([ '-x', '1' ]);466 assert.deepEqual(args, { x: 1 });467 args = parser.parseArgs([ '-x42' ]);468 assert.deepEqual(args, { x: 42 });469 assert.throws(function () {470 args = parser.parseArgs([ 'a' ]);471 });472 assert.throws(function () {473 args = parser.parseArgs([]);474 });475 });476 it('test a combination of single- and double-dash option strings', function () {477 parser = new ArgumentParser({ debug: true });478 parser.addArgument([ '-v', '--verbose', '-n', '--noisy' ], { action: 'storeTrue' });479 args = parser.parseArgs([]);480 assert.deepEqual(args, { verbose: false });481 args = parser.parseArgs([ '-v' ]);482 assert.deepEqual(args, { verbose: true });483 args = parser.parseArgs([ '--verbose' ]);484 assert.deepEqual(args, { verbose: true });485 args = parser.parseArgs([ '-n' ]);486 assert.deepEqual(args, { verbose: true });487 args = parser.parseArgs([ '--noisy' ]);488 assert.deepEqual(args, { verbose: true });489 assert.throws(function () {490 args = parser.parseArgs([ '--x', '--verbose' ]);491 });492 assert.throws(function () {493 args = parser.parseArgs([ '-N' ]);494 });495 assert.throws(function () {496 args = parser.parseArgs([ 'a' ]);497 });498 assert.throws(function () {499 args = parser.parseArgs([ '-v', 'x' ]);500 });501 });502 it('test an Optional with a single-dash option string', function () {503 parser = new ArgumentParser({ debug: true });504 parser.addArgument([ '-x' ], {});505 args = parser.parseArgs([]);506 assert.deepEqual(args, { x: null });507 args = parser.parseArgs([ '-x', 'a' ]);508 assert.deepEqual(args, { x: 'a' });509 args = parser.parseArgs([ '-xa' ]);510 assert.deepEqual(args, { x: 'a' });511 args = parser.parseArgs([ '-x', '-1' ]);512 assert.deepEqual(args, { x: '-1' });513 args = parser.parseArgs([ '-x-1' ]);514 assert.deepEqual(args, { x: '-1' });515 assert.throws(function () {516 args = parser.parseArgs([ '-x' ]);517 });518 assert.throws(function () {519 args = parser.parseArgs([ 'a' ]);520 });521 assert.throws(function () {522 args = parser.parseArgs([ '--foo' ]);523 });524 assert.throws(function () {525 args = parser.parseArgs([ '-x', '--foo' ]);526 });527 assert.throws(function () {528 args = parser.parseArgs([ '-x', '-y' ]);529 });530 });531 it('test Optionals that partially match but are not subsets', function () {532 parser = new ArgumentParser({ debug: true });533 parser.addArgument([ '-foobar' ], {});534 parser.addArgument([ '-foorab' ], {});535 args = parser.parseArgs([]);536 assert.deepEqual(args, { foorab: null, foobar: null });537 args = parser.parseArgs([ '-foob', 'a' ]);538 assert.deepEqual(args, { foorab: null, foobar: 'a' });539 args = parser.parseArgs([ '-foor', 'a' ]);540 assert.deepEqual(args, { foorab: 'a', foobar: null });541 args = parser.parseArgs([ '-fooba', 'a' ]);542 assert.deepEqual(args, { foorab: null, foobar: 'a' });543 args = parser.parseArgs([ '-foora', 'a' ]);544 assert.deepEqual(args, { foorab: 'a', foobar: null });545 args = parser.parseArgs([ '-foobar', 'a' ]);546 assert.deepEqual(args, { foorab: null, foobar: 'a' });547 args = parser.parseArgs([ '-foorab', 'a' ]);548 assert.deepEqual(args, { foorab: 'a', foobar: null });549 assert.throws(function () {550 args = parser.parseArgs([ '-f' ]);551 });552 assert.throws(function () {553 args = parser.parseArgs([ '-f', 'a' ]);554 });555 assert.throws(function () {556 args = parser.parseArgs([ '-fa' ]);557 });558 assert.throws(function () {559 args = parser.parseArgs([ '-foa' ]);560 });561 assert.throws(function () {562 args = parser.parseArgs([ '-foo' ]);563 });564 assert.throws(function () {565 args = parser.parseArgs([ '-fo' ]);566 });567 assert.throws(function () {568 args = parser.parseArgs([ '-foo', 'b' ]);569 });570 });571 it('test an Optional with a single-dash option string', function () {572 parser = new ArgumentParser({ debug: true });573 parser.addArgument([ '-x' ], { action: 'storeTrue' });574 parser.addArgument([ '-yyy' ], { action: 'storeConst', const: 42, constant: 42 });575 parser.addArgument([ '-z' ], {});576 args = parser.parseArgs([]);577 assert.deepEqual(args, { x: false, z: null, yyy: null });578 args = parser.parseArgs([ '-x' ]);579 assert.deepEqual(args, { x: true, z: null, yyy: null });580 args = parser.parseArgs([ '-za' ]);581 assert.deepEqual(args, { x: false, z: 'a', yyy: null });582 args = parser.parseArgs([ '-z', 'a' ]);583 assert.deepEqual(args, { x: false, z: 'a', yyy: null });584 args = parser.parseArgs([ '-xza' ]);585 assert.deepEqual(args, { x: true, z: 'a', yyy: null });586 args = parser.parseArgs([ '-xz', 'a' ]);587 assert.deepEqual(args, { x: true, z: 'a', yyy: null });588 args = parser.parseArgs([ '-x', '-za' ]);589 assert.deepEqual(args, { x: true, z: 'a', yyy: null });590 args = parser.parseArgs([ '-x', '-z', 'a' ]);591 assert.deepEqual(args, { x: true, z: 'a', yyy: null });592 args = parser.parseArgs([ '-y' ]);593 assert.deepEqual(args, { x: false, z: null, yyy: 42 });594 args = parser.parseArgs([ '-yyy' ]);595 assert.deepEqual(args, { x: false, z: null, yyy: 42 });596 args = parser.parseArgs([ '-x', '-yyy', '-za' ]);597 assert.deepEqual(args, { x: true, z: 'a', yyy: 42 });598 args = parser.parseArgs([ '-x', '-yyy', '-z', 'a' ]);599 assert.deepEqual(args, { x: true, z: 'a', yyy: 42 });600 assert.throws(function () {601 args = parser.parseArgs([ 'a' ]);602 });603 assert.throws(function () {604 args = parser.parseArgs([ '--foo' ]);605 });606 assert.throws(function () {607 args = parser.parseArgs([ '-xa' ]);608 });609 assert.throws(function () {610 args = parser.parseArgs([ '-x', '--foo' ]);611 });612 assert.throws(function () {613 args = parser.parseArgs([ '-x', '-z' ]);614 });615 assert.throws(function () {616 args = parser.parseArgs([ '-z', '-x' ]);617 });618 assert.throws(function () {619 args = parser.parseArgs([ '-yx' ]);620 });621 assert.throws(function () {622 args = parser.parseArgs([ '-yz', 'a' ]);623 });624 assert.throws(function () {625 args = parser.parseArgs([ '-yyyx' ]);626 });627 assert.throws(function () {628 args = parser.parseArgs([ '-yyyza' ]);629 });630 assert.throws(function () {631 args = parser.parseArgs([ '-xyza' ]);632 });633 });634 it('test an Optional with a multi-character single-dash option string', function () {635 parser = new ArgumentParser({ debug: true });636 parser.addArgument([ '-foo' ], {});637 args = parser.parseArgs([]);638 assert.deepEqual(args, { foo: null });639 args = parser.parseArgs([ '-foo', 'a' ]);640 assert.deepEqual(args, { foo: 'a' });641 args = parser.parseArgs([ '-foo', '-1' ]);642 assert.deepEqual(args, { foo: '-1' });643 args = parser.parseArgs([ '-fo', 'a' ]);644 assert.deepEqual(args, { foo: 'a' });645 args = parser.parseArgs([ '-f', 'a' ]);646 assert.deepEqual(args, { foo: 'a' });647 assert.throws(function () {648 args = parser.parseArgs([ '-foo' ]);649 });650 assert.throws(function () {651 args = parser.parseArgs([ 'a' ]);652 });653 assert.throws(function () {654 args = parser.parseArgs([ '--foo' ]);655 });656 assert.throws(function () {657 args = parser.parseArgs([ '-foo', '--foo' ]);658 });659 assert.throws(function () {660 args = parser.parseArgs([ '-foo', '-y' ]);661 });662 assert.throws(function () {663 args = parser.parseArgs([ '-fooa' ]);664 });665 });666 it('test Optionals where option strings are subsets of each other', function () {667 parser = new ArgumentParser({ debug: true });668 parser.addArgument([ '-f' ], {});669 parser.addArgument([ '-foobar' ], {});670 parser.addArgument([ '-foorab' ], {});671 args = parser.parseArgs([]);672 assert.deepEqual(args, { foorab: null, f: null, foobar: null });673 args = parser.parseArgs([ '-f', 'a' ]);674 assert.deepEqual(args, { foorab: null, f: 'a', foobar: null });675 args = parser.parseArgs([ '-fa' ]);676 assert.deepEqual(args, { foorab: null, f: 'a', foobar: null });677 args = parser.parseArgs([ '-foa' ]);678 assert.deepEqual(args, { foorab: null, f: 'oa', foobar: null });679 args = parser.parseArgs([ '-fooa' ]);680 assert.deepEqual(args, { foorab: null, f: 'ooa', foobar: null });681 args = parser.parseArgs([ '-foobar', 'a' ]);682 assert.deepEqual(args, { foorab: null, f: null, foobar: 'a' });683 args = parser.parseArgs([ '-foorab', 'a' ]);684 assert.deepEqual(args, { foorab: 'a', f: null, foobar: null });685 assert.throws(function () {686 args = parser.parseArgs([ '-f' ]);687 });688 assert.throws(function () {689 args = parser.parseArgs([ '-foo' ]);690 });691 assert.throws(function () {692 args = parser.parseArgs([ '-fo' ]);693 });694 assert.throws(function () {695 args = parser.parseArgs([ '-foo', 'b' ]);696 });697 assert.throws(function () {698 args = parser.parseArgs([ '-foob' ]);699 });700 assert.throws(function () {701 args = parser.parseArgs([ '-fooba' ]);702 });703 assert.throws(function () {704 args = parser.parseArgs([ '-foora' ]);705 });706 });707 it('test an Optional with single- and double-dash option strings', function () {708 parser = new ArgumentParser({ debug: true });709 parser.addArgument([ '-f' ], { action: 'storeTrue' });710 parser.addArgument([ '--bar' ], {});711 parser.addArgument([ '-baz' ], { action: 'storeConst', const: 42, constant: 42 });712 args = parser.parseArgs([]);713 assert.deepEqual(args, { bar: null, baz: null, f: false });714 args = parser.parseArgs([ '-f' ]);715 assert.deepEqual(args, { bar: null, baz: null, f: true });716 args = parser.parseArgs([ '--ba', 'B' ]);717 assert.deepEqual(args, { bar: 'B', baz: null, f: false });718 args = parser.parseArgs([ '-f', '--bar', 'B' ]);719 assert.deepEqual(args, { bar: 'B', baz: null, f: true });720 args = parser.parseArgs([ '-f', '-b' ]);721 assert.deepEqual(args, { bar: null, baz: 42, f: true });722 args = parser.parseArgs([ '-ba', '-f' ]);723 assert.deepEqual(args, { bar: null, baz: 42, f: true });724 assert.throws(function () {725 args = parser.parseArgs([ '--bar' ]);726 });727 assert.throws(function () {728 args = parser.parseArgs([ '-fbar' ]);729 });730 assert.throws(function () {731 args = parser.parseArgs([ '-fbaz' ]);732 });733 assert.throws(function () {734 args = parser.parseArgs([ '-bazf' ]);735 });736 assert.throws(function () {737 args = parser.parseArgs([ '-b', 'B' ]);738 });739 assert.throws(function () {740 args = parser.parseArgs([ 'B' ]);741 });742 });743});...
drive_error_injection_cli.py
Source:drive_error_injection_cli.py
1#!/usr/bin/env python2import cmd3import sys4import socket5import argparse6import os7import json8import re9from copy import deepcopy10line = """11==========================================================================12"""13errorinjection_help = """14+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++15Support commands:16 list List all device id17 nvme Inject error18 show Show error status for all device19 nvmeclear Clean error20 scsi_logpage Inject data to logpage21 scsi_status Inject scsi status error22 scsiclear Clear scsi error23 history Show qmp command history24+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++25"""26nvmeclear_help = """27usage: nvmeclear <id>28clear nvme error on a device29"""30history_command=[]31def connect_monitor(monitor_file):32 if not os.path.exists(monitor_file):33 return None34 monitor = Monitor(monitor_file)35 try:36 monitor.connect()37 except IOError:38 return None39 return monitor40def get_device_list(monitor, device_type):41 payload = {42 "execute": "human-monitor-command",43 "arguments":{44 "command-line":"info block"45 }46 }47 monitor.send(payload)48 results = monitor.recv()49 if 'error' not in str(results):50 returns = results.get('return')51 device_list = re.findall(r'Attached to:\s+(\S+)', returns, re.M)52 return [x for x in device_list if device_type in x]53 else:54 return None55def get_device_list_info(monitor, device_list):56 payload = {57 "execute": "human-monitor-command",58 "arguments": {59 "command-line": "info qtree"60 }61 }62 monitor.send(payload)63 results = monitor.recv()64 dev_list_info = {}65 returns = str(results.get('return')).split("dev:")[1:]66 for device_id in device_list:67 for dev in returns:68 if device_id in dev:69 dev_list_info[device_id] = re.findall(r'serial = "(\S+)"', dev)[0]70 break71 return dev_list_info72class Monitor(object):73 def __init__(self, path):74 self.path = path75 self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)76 def connect(self):77 self.s.connect(self.path)78 self.recv()79 payload = {80 "execute": "qmp_capabilities"81 }82 self.send(payload)83 self.recv()84 def send(self, payload):85 self.s.send(json.dumps(payload))86 def recv(self):87 while 1:88 rsp = ""89 while 1:90 snip = self.s.recv(1024)91 rsp += snip92 if len(snip) < 1024:93 break94 if "timestamp" not in rsp:95 break96 return json.loads(rsp)97 def close(self):98 self.s.shutdown(2)99 self.s.close()100 def shutdown_recv(self):101 self.s.shutdown(0)102def list_argparse():103 parser = argparse.ArgumentParser(prog="list",104 usage="list all device id")105 parser.add_argument("-u", "--update", action="store", required=False,106 help="update nvme device id")107 return parser108def nvmeclear_argparse():109 parser = argparse.ArgumentParser(prog="nvmeclear")110 parser.add_argument("-i", "--id", action="store", required=False,111 default=None, help="nvme device id")112 return parser113def scsiclear_argparse():114 parser = argparse.ArgumentParser(prog="scsiclear")115 parser.add_argument("-i", "--id", action="store", required=False,116 default=None, help="scsi device id")117 return parser118def nvme_argparse():119 parser = argparse.ArgumentParser(prog="nvme")120 parser.add_argument("-i", "--id", action="store", required=False,121 default=None, help="nvme device id")122 parser.add_argument("-n", "--nsid", action="store", required=False,123 default=1, help="nvme namespace id")124 parser.add_argument("-s", "--sc", action="store", required=False,125 default=None, help="status code")126 parser.add_argument("-t", "--sct", action="store", required=False,127 default=None, help="status code type")128 error_help = "Support nvme error type: {}".format(", ".join(error_map.keys()))129 parser.add_argument("-e", "--error", action="store", required=False,130 default=None, help=error_help)131 parser.add_argument("-m", "--more", action="store", required=False,132 default=True, help="more info in Error Information log")133 parser.add_argument("-d", "--dnr", action="store", required=False,134 default=True, help="do not retry")135 opcode_help = "support : flush, write, read, write_uncor, \136 compare, write_zeros, dsm, rw"137 parser.add_argument("-o", "--opcode", action="store", required=False,138 default="rw", help=opcode_help)139 parser.add_argument("-c", "--count", action="store", required=False,140 default=65536, help="error inject available times")141 parser.add_argument("-l", "--lbas", action="store", required=False,142 help="logical block address")143 return parser144def scsi_logpage_argparse():145 parser = argparse.ArgumentParser(prog="scsi_logpage")146 parser.add_argument("-i", "--id", action="store", required=False,147 default=None, help="scsi device id")148 error_help = "support page type: life_used, erase_count, temperature"149 parser.add_argument("-t", "--type", action="store", required=True,150 default=None, help=error_help)151 parser.add_argument("-a", "--action", action="store", required=True,152 default=None, help="support actions: add, remove, modify")153 parser.add_argument("-p", "--parameter", action="store", required=False,154 default=None, help="parameter in logpage")155 parser.add_argument("-pl", "--parameter_len", action="store", required=False,156 default=4, help="parameter length in byte")157 parser.add_argument("-v", "--value", action="store", required=False,158 default=None, help="scsi device id")159 return parser160def scsi_status_argparse():161 parser = argparse.ArgumentParser(prog="scsi_status", formatter_class=argparse.RawTextHelpFormatter,162 description='Inject status error to drive. Injected error will cleaned automatically after cli exit.')163 parser.add_argument("-i", "--id", action="store", required=False,164 default=None, help="scsi device id")165 error_types = ["check-condition", "condition-met", "busy", "reservation-conflict",166 "task-set-full", "aca-active", "task-aborted"]167 parser.add_argument("-c", "--count", action="store", required=False,168 default=65536, help="error inject available times")169 parser.add_argument("-t", dest="type", action="store", required=False,170 choices=error_types,171 default="busy",172 metavar='TYPE',173 help="scsi status error type:\n" + "\n".join(error_types))174 parser.add_argument("-l", "--lbas", action="store", required=False,175 default=0, help="lbas list")176 group = parser.add_mutually_exclusive_group()177 group.add_argument("-s", "--sense", action="store", required=False, metavar='N',178 default=None, type=lambda x: int(x, 0), nargs=3, help="sense_code [key asc ascq].\nRefer to https://en.wikipedia.org/wiki/Key_Code_Qualifier")179 error_keys = scsi_status_error_map.keys()180 error_help = "Supported scsi sense code string:\n{}".format("\n".join(error_keys))181 group.add_argument("-e", "--error", action="store", required=False, metavar='ERROR',182 choices=error_keys, default=None, help=error_help)183 return parser184def history_record(command):185 history_command.append(command)186def show_record():187 for cmd in history_command:188 print cmd189class ErrorInjectCli(cmd.Cmd):190 def __init__(self, monitor):191 cmd.Cmd.__init__(self)192 self._monitor = monitor193 self._list_args = None194 self._nvme_args = None195 self._scsi_args = None196 self._nvmeclear_args = None197 self.prompt = "EI> "198 self._nvme_id_list_injected = {}199 self._scsi_id_list_injected = {}200 self._nvme_id_list_all = []201 def init(self):202 self._nvme_id_list_all = get_device_list(self._monitor, "nvme")203 self._scsi_id_list_all = get_device_list(self._monitor, 'scsi')204 self._list_args = list_argparse()205 self._nvme_args = nvme_argparse()206 self._scsi_logpage_args = scsi_logpage_argparse()207 self._scsi_status_args = scsi_status_argparse()208 self._nvmeclear_args = nvmeclear_argparse()209 self._scsiclear_args = scsiclear_argparse()210 def do_show(self, args):211 for id in self._nvme_id_list_all:212 if self._nvme_id_list_injected.has_key(id):213 error = self._nvme_id_list_injected[id]214 out_str = "{} {}".format(id, error)215 else:216 out_str = "{} NoError".format(id)217 print out_str218 for id in self._scsi_id_list_all:219 if self._scsi_id_list_injected.has_key(id):220 error = self._scsi_id_list_injected[id]221 out_str = "{} {}".format(id, error)222 else:223 out_str = "{} NoError".format(id)224 print out_str225 def do_history(self, args):226 show_record()227 def emptyline(self):228 return ""229 def do_help(self, args):230 if args:231 if args == "nvme":232 self.do_nvme("--help")233 if args == "scsi_logpage":234 self.do_scsi_logpage("--help")235 elif args == "nvmeclear":236 self.do_nvmeclear("--help")237 elif args == "list":238 self.do_list("--help")239 else:240 return241 else:242 print errorinjection_help243 self.do_nvme("--help")244 print line245 self.do_nvmeclear("--help")246 print line247 self.do_list("--help")248 print line249 self.do_scsi_logpage("--help")250 print line251 self.do_scsi_status('--help')252 def do_nvmeclear(self, args):253 args_list = args.split()254 try:255 parseargs = self._nvmeclear_args.parse_args(args_list)256 except SystemExit as e:257 return258 if parseargs.id:259 nvme_args = "-i {} -n 0 -s 0 -t 0 -c 0".format(parseargs.id)260 self.do_nvme(nvme_args)261 else:262 # clear all device error263 nvme_dict = self._nvme_id_list_injected264 for key in nvme_dict.keys():265 nvme_args = "-i {} -n 0 -s 0 -t 0 -c 0".format(key)266 self.do_nvme(nvme_args)267 def do_scsiclear(self, args):268 args_list = args.split()269 try:270 parseargs = self._scsiclear_args.parse_args(args_list)271 except SystemExit as e:272 return273 if parseargs.id:274 scsi_args = "-i {} -c 0".format(parseargs.id)275 self.do_scsi_status(scsi_args)276 else:277 # clear all device error278 scsi_dict = self._scsi_id_list_injected279 for key in scsi_dict.keys():280 scsi_args = "-i {} -c 0".format(key)281 self.do_scsi_status(scsi_args)282 def do_nvme(self, args):283 args_list = args.split()284 try:285 parseargs = self._nvme_args.parse_args(args_list)286 except SystemExit as e:287 return288 monitor = self._monitor289 if parseargs.error and error_map.has_key(parseargs.error):290 parseargs.sc = error_map[parseargs.error]['sc']291 parseargs.sct = error_map[parseargs.error]['sct']292 if error_map[parseargs.error].has_key('opcode'):293 parseargs.opcode = error_map[parseargs.error]['opcode']294 elif parseargs.sc is None or parseargs.sct is None:295 print "[Error]: please at least config (SC & SCT) or (ERROR)"296 print "eg: nvme -e internal-error"297 print line298 self.do_nvme("--help")299 return300 # check sc and sct validition301 status_field = {302 "sc": int(parseargs.sc),303 "sct": int(parseargs.sct),304 "more": parseargs.more,305 "dnr": parseargs.dnr306 }307 cmd = {308 "nsid": int(parseargs.nsid),309 "status_field": status_field,310 "opcode": parseargs.opcode,311 "count": int(parseargs.count),312 }313 if parseargs.lbas:314 cmd['lbas'] = [int(parseargs.lbas)]315 cmd_list = []316 if not parseargs.id: # not set id, will inject to all drive317 for id in self._nvme_id_list_all:318 cmd_new = deepcopy(cmd)319 cmd_new['id'] = id320 cmd_list.append(cmd_new)321 else:322 cmd['id'] = parseargs.id323 cmd_list.append(cmd) # only one cmd324 for command in cmd_list:325 payload = {326 "execute": "nvme-status-code-error-inject",327 "arguments": command328 }329 monitor.send(payload)330 results = monitor.recv()331 if 'error' not in str(results):332 if command["count"]:333 print "Inject Done: {}".format(command['id'])334 self._nvme_id_list_injected[command['id']] = parseargs.error335 else:336 print "Clean Done: {}".format(command["id"])337 self._nvme_id_list_injected.pop(command['id'])338 record = 'Inject Success: {}'.format(command)339 else:340 print results341 record = 'Inject Failed: {}'.format(command)342 history_record(record)343 def do_list(self, args):344 args_list = args.split()345 try:346 parseargs = self._list_args.parse_args(args_list)347 except SystemExit as e:348 return349 if parseargs.update:350 print '<<<<<<<<<<<<<< update device id >>>>>>>>>>>>>>>'351 self._nvme_id_list_all = get_device_list(self._monitor, 'nvme')352 self._scsi_id_list_all = get_device_list(self._monitor, 'scsi')353 nvme_device_info = get_device_list_info(self._monitor, self._nvme_id_list_all)354 scsi_device_info = get_device_list_info(self._monitor, self._scsi_id_list_all)355 for id in self._nvme_id_list_all:356 print id, "({})".format(nvme_device_info.get(id, None))357 for id in self._scsi_id_list_all:358 print id, "({})".format(scsi_device_info.get(id, None))359 def do_scsi_logpage(self, args):360 args_list = args.split()361 try:362 parseargs = self._scsi_logpage_args.parse_args(args_list)363 except SystemExit as e:364 return365 monitor = self._monitor366 if 'add' in parseargs.type and not parseargs.value:367 print 'Error: add need a value'368 return369 # check sc and sct validition370 cmd = {371 "type": parseargs.type,372 "action": parseargs.action,373 }374 if parseargs.parameter:375 cmd['parameter'] = int(parseargs.parameter)376 if parseargs.parameter_len:377 cmd['parameter_length'] = int(parseargs.parameter_len)378 if parseargs.value:379 cmd['val'] = int(parseargs.value)380 cmd_list = []381 if not parseargs.id: # not set id, will inject to all drive382 for id in self._scsi_id_list_all:383 cmd_new = deepcopy(cmd)384 cmd_new['id'] = id385 cmd_list.append(cmd_new)386 else:387 cmd['id'] = parseargs.id388 cmd_list.append(cmd) # only one cmd389 for command in cmd_list:390 payload = {391 "execute": "scsi-drive-error-inject",392 "arguments": command393 }394 monitor.send(payload)395 results = monitor.recv()396 if 'error' not in str(results):397 record = 'Inject Success: {}'.format(command)398 else:399 print results400 record = 'Inject Failed: {}'.format(command)401 history_record(record)402 def do_scsi_status(self, args):403 args_list = args.split()404 try:405 parseargs = self._scsi_status_args.parse_args(args_list)406 except SystemExit as e:407 return408 monitor = self._monitor409 cmd = {}410 if parseargs.error or parseargs.sense:411 print "[Warning]: type is set to 'check-condition' when error or sense is specified."412 parseargs.type = "check-condition"413 if parseargs.error:414 sense_key = scsi_status_error_map[parseargs.error]['key']415 sense_asc = scsi_status_error_map[parseargs.error]['asc']416 sense_ascq = scsi_status_error_map[parseargs.error]['ascq']417 if parseargs.sense:418 sense_key = parseargs.sense[0]419 sense_asc = parseargs.sense[1]420 sense_ascq = parseargs.sense[2]421 # check sc and sct validition422 sense_field = {423 "key": sense_key,424 "asc": sense_asc,425 "ascq": sense_ascq,426 }427 cmd['sense'] = sense_field428 cmd["count"] = int(parseargs.count)429 cmd["error_type"] = parseargs.type430 if parseargs.lbas:431 cmd['lbas'] = [int(parseargs.lbas)]432 cmd_list = []433 if not parseargs.id: # not set id, will inject to all drive434 for id in self._scsi_id_list_all:435 cmd_new = deepcopy(cmd)436 cmd_new['id'] = id437 cmd_list.append(cmd_new)438 else:439 cmd['id'] = parseargs.id440 cmd_list.append(cmd) # only one cmd441 for cmd in cmd_list:442 print(cmd)443 for command in cmd_list:444 payload = {445 "execute": "scsi-status-code-error-inject",446 "arguments": command447 }448 monitor.send(payload)449 results = monitor.recv()450 if 'error' not in str(results):451 record = 'Inject Success: {}'.format(command)452 if command["count"]:453 print "Inject Done: {}".format(command['id'])454 self._scsi_id_list_injected[command['id']] = parseargs.type455 else:456 print "Clean Done: {}".format(command["id"])457 if command['id'] in self._scsi_id_list_injected:458 self._scsi_id_list_injected.pop(command['id'])459 else:460 print results461 record = 'Inject Failed: {}'.format(command)462 history_record(record)463 def do_quit(self, args):464 self.do_nvmeclear("")465 self.do_scsiclear("")466 return True467 def do_exit(self, args):468 self.do_nvmeclear("")469 self.do_scsiclear("")470 sys.exit(0)471scsi_status_error_map = {472 # add more error type here if needed473 'medium-error': {'key':3, 'asc':17, 'ascq':0}474}475error_map = {476 'data_transfer_error': {'sc':4, 'sct':0},477 'commands-aborted': {'sc':5, 'sct':0},478 'internal-error': {'sc':6, 'sct':0},479 'namespace-not-ready': {'sc':130, 'sct':0},480 'format-in-process': {'sc':131, 'sct':0},481 'write-fault': {'sc':128, 'sct':2, 'opcode':'write'},482 'unrecovered-read-error': {'sc':129, 'sct':2, 'opcode':'read'},483 'endtoend-guard-check-error': {'sc':130, 'sct':2, 'opcode':'read'},484 'endtoend-application-tag-check-error': {'sc':131, 'sct':2},485 'endtoend-reference-tag-check-error': {'sc':132, 'sct':2},486 'compare-failure': {'sc':133, 'sct':2},487 'access-denied': {'sc':134, 'sct':2},488 'deallocated-or-unwritten': {'sc':135, 'sct':2}489}490def main():491 description = "Attention: '-N' or '-M' could not appear together!"492 parser = argparse.ArgumentParser(description = description)493 parser.add_argument("-N", "--nodename", action="store", required=False,494 help="node name")495 parser.add_argument("-M", "--monitor", action="store", required=False,496 help="path of .monitor")497 args = parser.parse_args()498 if not (not args.nodename) ^ (not args.monitor):499 print "[ERROR] -N or -M need to be set, (can only choose one!)"500 return501 if args.nodename:502 monitor_path = os.path.join(os.environ['HOME'],503 ".infrasim", args.nodename,504 '.monitor')505 else:506 monitor_path = args.monitor507 if not os.path.exists(monitor_path):508 print "Could not find monitor file {}".format(monitor_path)509 return510 monitor = connect_monitor(monitor_path)511 if not monitor:512 print "Could not connect to monitor!"513 return514 cli = ErrorInjectCli(monitor)515 cli.init()516 try:517 cli.cmdloop()518 except KeyboardInterrupt as e:519 print "receive keyboard interrupt, will exit"520 cli.do_exit(None)521if __name__ == '__main__':...
test-parse-args.mjs
Source:test-parse-args.mjs
...4import { parseArgs } from 'node:util';5test('when short option used as flag then stored as flag', () => {6 const args = ['-f'];7 const expected = { values: { __proto__: null, f: true }, positionals: [] };8 const result = parseArgs({ strict: false, args });9 assert.deepStrictEqual(result, expected);10});11test('when short option used as flag before positional then stored as flag and positional (and not value)', () => {12 const args = ['-f', 'bar'];13 const expected = { values: { __proto__: null, f: true }, positionals: [ 'bar' ] };14 const result = parseArgs({ strict: false, args });15 assert.deepStrictEqual(result, expected);16});17test('when short option `type: "string"` used with value then stored as value', () => {18 const args = ['-f', 'bar'];19 const options = { f: { type: 'string' } };20 const expected = { values: { __proto__: null, f: 'bar' }, positionals: [] };21 const result = parseArgs({ args, options });22 assert.deepStrictEqual(result, expected);23});24test('when short option listed in short used as flag then long option stored as flag', () => {25 const args = ['-f'];26 const options = { foo: { short: 'f', type: 'boolean' } };27 const expected = { values: { __proto__: null, foo: true }, positionals: [] };28 const result = parseArgs({ args, options });29 assert.deepStrictEqual(result, expected);30});31test('when short option listed in short and long listed in `type: "string"` and ' +32 'used with value then long option stored as value', () => {33 const args = ['-f', 'bar'];34 const options = { foo: { short: 'f', type: 'string' } };35 const expected = { values: { __proto__: null, foo: 'bar' }, positionals: [] };36 const result = parseArgs({ args, options });37 assert.deepStrictEqual(result, expected);38});39test('when short option `type: "string"` used without value then stored as flag', () => {40 const args = ['-f'];41 const options = { f: { type: 'string' } };42 const expected = { values: { __proto__: null, f: true }, positionals: [] };43 const result = parseArgs({ strict: false, args, options });44 assert.deepStrictEqual(result, expected);45});46test('short option group behaves like multiple short options', () => {47 const args = ['-rf'];48 const options = { };49 const expected = { values: { __proto__: null, r: true, f: true }, positionals: [] };50 const result = parseArgs({ strict: false, args, options });51 assert.deepStrictEqual(result, expected);52});53test('short option group does not consume subsequent positional', () => {54 const args = ['-rf', 'foo'];55 const options = { };56 const expected = { values: { __proto__: null, r: true, f: true }, positionals: ['foo'] };57 const result = parseArgs({ strict: false, args, options });58 assert.deepStrictEqual(result, expected);59});60// See: Guideline 5 https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html61test('if terminal of short-option group configured `type: "string"`, subsequent positional is stored', () => {62 const args = ['-rvf', 'foo'];63 const options = { f: { type: 'string' } };64 const expected = { values: { __proto__: null, r: true, v: true, f: 'foo' }, positionals: [] };65 const result = parseArgs({ strict: false, args, options });66 assert.deepStrictEqual(result, expected);67});68test('handles short-option groups in conjunction with long-options', () => {69 const args = ['-rf', '--foo', 'foo'];70 const options = { foo: { type: 'string' } };71 const expected = { values: { __proto__: null, r: true, f: true, foo: 'foo' }, positionals: [] };72 const result = parseArgs({ strict: false, args, options });73 assert.deepStrictEqual(result, expected);74});75test('handles short-option groups with "short" alias configured', () => {76 const args = ['-rf'];77 const options = { remove: { short: 'r', type: 'boolean' } };78 const expected = { values: { __proto__: null, remove: true, f: true }, positionals: [] };79 const result = parseArgs({ strict: false, args, options });80 assert.deepStrictEqual(result, expected);81});82test('handles short-option followed by its value', () => {83 const args = ['-fFILE'];84 const options = { foo: { short: 'f', type: 'string' } };85 const expected = { values: { __proto__: null, foo: 'FILE' }, positionals: [] };86 const result = parseArgs({ strict: false, args, options });87 assert.deepStrictEqual(result, expected);88});89test('Everything after a bare `--` is considered a positional argument', () => {90 const args = ['--', 'barepositionals', 'mopositionals'];91 const expected = { values: { __proto__: null }, positionals: ['barepositionals', 'mopositionals'] };92 const result = parseArgs({ allowPositionals: true, args });93 assert.deepStrictEqual(result, expected, Error('testing bare positionals'));94});95test('args are true', () => {96 const args = ['--foo', '--bar'];97 const expected = { values: { __proto__: null, foo: true, bar: true }, positionals: [] };98 const result = parseArgs({ strict: false, args });99 assert.deepStrictEqual(result, expected, Error('args are true'));100});101test('arg is true and positional is identified', () => {102 const args = ['--foo=a', '--foo', 'b'];103 const expected = { values: { __proto__: null, foo: true }, positionals: ['b'] };104 const result = parseArgs({ strict: false, args });105 assert.deepStrictEqual(result, expected, Error('arg is true and positional is identified'));106});107test('args equals are passed `type: "string"`', () => {108 const args = ['--so=wat'];109 const options = { so: { type: 'string' } };110 const expected = { values: { __proto__: null, so: 'wat' }, positionals: [] };111 const result = parseArgs({ args, options });112 assert.deepStrictEqual(result, expected, Error('arg value is passed'));113});114test('when args include single dash then result stores dash as positional', () => {115 const args = ['-'];116 const expected = { values: { __proto__: null }, positionals: ['-'] };117 const result = parseArgs({ allowPositionals: true, args });118 assert.deepStrictEqual(result, expected);119});120test('zero config args equals are parsed as if `type: "string"`', () => {121 const args = ['--so=wat'];122 const options = { };123 const expected = { values: { __proto__: null, so: 'wat' }, positionals: [] };124 const result = parseArgs({ strict: false, args, options });125 assert.deepStrictEqual(result, expected, Error('arg value is passed'));126});127test('same arg is passed twice `type: "string"` and last value is recorded', () => {128 const args = ['--foo=a', '--foo', 'b'];129 const options = { foo: { type: 'string' } };130 const expected = { values: { __proto__: null, foo: 'b' }, positionals: [] };131 const result = parseArgs({ args, options });132 assert.deepStrictEqual(result, expected, Error('last arg value is passed'));133});134test('args equals pass string including more equals', () => {135 const args = ['--so=wat=bing'];136 const options = { so: { type: 'string' } };137 const expected = { values: { __proto__: null, so: 'wat=bing' }, positionals: [] };138 const result = parseArgs({ args, options });139 assert.deepStrictEqual(result, expected, Error('arg value is passed'));140});141test('first arg passed for `type: "string"` and "multiple" is in array', () => {142 const args = ['--foo=a'];143 const options = { foo: { type: 'string', multiple: true } };144 const expected = { values: { __proto__: null, foo: ['a'] }, positionals: [] };145 const result = parseArgs({ args, options });146 assert.deepStrictEqual(result, expected, Error('first multiple in array'));147});148test('args are passed `type: "string"` and "multiple"', () => {149 const args = ['--foo=a', '--foo', 'b'];150 const options = {151 foo: {152 type: 'string',153 multiple: true,154 },155 };156 const expected = { values: { __proto__: null, foo: ['a', 'b'] }, positionals: [] };157 const result = parseArgs({ args, options });158 assert.deepStrictEqual(result, expected, Error('both arg values are passed'));159});160test('when expecting `multiple:true` boolean option and option used multiple times then result includes array of ' +161 'booleans matching usage', () => {162 const args = ['--foo', '--foo'];163 const options = {164 foo: {165 type: 'boolean',166 multiple: true,167 },168 };169 const expected = { values: { __proto__: null, foo: [true, true] }, positionals: [] };170 const result = parseArgs({ args, options });171 assert.deepStrictEqual(result, expected);172});173test('order of option and positional does not matter (per README)', () => {174 const args1 = ['--foo=bar', 'baz'];175 const args2 = ['baz', '--foo=bar'];176 const options = { foo: { type: 'string' } };177 const expected = { values: { __proto__: null, foo: 'bar' }, positionals: ['baz'] };178 assert.deepStrictEqual(179 parseArgs({ allowPositionals: true, args: args1, options }),180 expected,181 Error('option then positional')182 );183 assert.deepStrictEqual(184 parseArgs({ allowPositionals: true, args: args2, options }),185 expected,186 Error('positional then option')187 );188});189test('correct default args when use node -p', () => {190 const holdArgv = process.argv;191 process.argv = [process.argv0, '--foo'];192 const holdExecArgv = process.execArgv;193 process.execArgv = ['-p', '0'];194 const result = parseArgs({ strict: false });195 const expected = { values: { __proto__: null, foo: true },196 positionals: [] };197 assert.deepStrictEqual(result, expected);198 process.argv = holdArgv;199 process.execArgv = holdExecArgv;200});201test('correct default args when use node --print', () => {202 const holdArgv = process.argv;203 process.argv = [process.argv0, '--foo'];204 const holdExecArgv = process.execArgv;205 process.execArgv = ['--print', '0'];206 const result = parseArgs({ strict: false });207 const expected = { values: { __proto__: null, foo: true },208 positionals: [] };209 assert.deepStrictEqual(result, expected);210 process.argv = holdArgv;211 process.execArgv = holdExecArgv;212});213test('correct default args when use node -e', () => {214 const holdArgv = process.argv;215 process.argv = [process.argv0, '--foo'];216 const holdExecArgv = process.execArgv;217 process.execArgv = ['-e', '0'];218 const result = parseArgs({ strict: false });219 const expected = { values: { __proto__: null, foo: true },220 positionals: [] };221 assert.deepStrictEqual(result, expected);222 process.argv = holdArgv;223 process.execArgv = holdExecArgv;224});225test('correct default args when use node --eval', () => {226 const holdArgv = process.argv;227 process.argv = [process.argv0, '--foo'];228 const holdExecArgv = process.execArgv;229 process.execArgv = ['--eval', '0'];230 const result = parseArgs({ strict: false });231 const expected = { values: { __proto__: null, foo: true },232 positionals: [] };233 assert.deepStrictEqual(result, expected);234 process.argv = holdArgv;235 process.execArgv = holdExecArgv;236});237test('correct default args when normal arguments', () => {238 const holdArgv = process.argv;239 process.argv = [process.argv0, 'script.js', '--foo'];240 const holdExecArgv = process.execArgv;241 process.execArgv = [];242 const result = parseArgs({ strict: false });243 const expected = { values: { __proto__: null, foo: true },244 positionals: [] };245 assert.deepStrictEqual(result, expected);246 process.argv = holdArgv;247 process.execArgv = holdExecArgv;248});249test('excess leading dashes on options are retained', () => {250 // Enforce a design decision for an edge case.251 const args = ['---triple'];252 const options = { };253 const expected = {254 values: { '__proto__': null, '-triple': true },255 positionals: []256 };257 const result = parseArgs({ strict: false, args, options });258 assert.deepStrictEqual(result, expected, Error('excess option dashes are retained'));259});260test('positional arguments are allowed by default in strict:false', () => {261 const args = ['foo'];262 const options = { };263 const expected = {264 values: { __proto__: null },265 positionals: ['foo']266 };267 const result = parseArgs({ strict: false, args, options });268 assert.deepStrictEqual(result, expected);269});270test('positional arguments may be explicitly disallowed in strict:false', () => {271 const args = ['foo'];272 const options = { };273 assert.throws(() => { parseArgs({ strict: false, allowPositionals: false, args, options }); }, {274 code: 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL'275 });276});277// Test bad inputs278test('invalid argument passed for options', () => {279 const args = ['--so=wat'];280 const options = 'bad value';281 assert.throws(() => { parseArgs({ args, options }); }, {282 code: 'ERR_INVALID_ARG_TYPE'283 });284});285test('type property missing for option then throw', () => {286 const knownOptions = { foo: { } };287 assert.throws(() => { parseArgs({ options: knownOptions }); }, {288 code: 'ERR_INVALID_ARG_TYPE'289 });290});291test('boolean passed to "type" option', () => {292 const args = ['--so=wat'];293 const options = { foo: { type: true } };294 assert.throws(() => { parseArgs({ args, options }); }, {295 code: 'ERR_INVALID_ARG_TYPE'296 });297});298test('invalid union value passed to "type" option', () => {299 const args = ['--so=wat'];300 const options = { foo: { type: 'str' } };301 assert.throws(() => { parseArgs({ args, options }); }, {302 code: 'ERR_INVALID_ARG_TYPE'303 });304});305// Test strict mode306test('unknown long option --bar', () => {307 const args = ['--foo', '--bar'];308 const options = { foo: { type: 'boolean' } };309 assert.throws(() => { parseArgs({ args, options }); }, {310 code: 'ERR_PARSE_ARGS_UNKNOWN_OPTION'311 });312});313test('unknown short option -b', () => {314 const args = ['--foo', '-b'];315 const options = { foo: { type: 'boolean' } };316 assert.throws(() => { parseArgs({ args, options }); }, {317 code: 'ERR_PARSE_ARGS_UNKNOWN_OPTION'318 });319});320test('unknown option -r in short option group -bar', () => {321 const args = ['-bar'];322 const options = { b: { type: 'boolean' }, a: { type: 'boolean' } };323 assert.throws(() => { parseArgs({ args, options }); }, {324 code: 'ERR_PARSE_ARGS_UNKNOWN_OPTION'325 });326});327test('unknown option with explicit value', () => {328 const args = ['--foo', '--bar=baz'];329 const options = { foo: { type: 'boolean' } };330 assert.throws(() => { parseArgs({ args, options }); }, {331 code: 'ERR_PARSE_ARGS_UNKNOWN_OPTION'332 });333});334test('unexpected positional', () => {335 const args = ['foo'];336 const options = { foo: { type: 'boolean' } };337 assert.throws(() => { parseArgs({ args, options }); }, {338 code: 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL'339 });340});341test('unexpected positional after --', () => {342 const args = ['--', 'foo'];343 const options = { foo: { type: 'boolean' } };344 assert.throws(() => { parseArgs({ args, options }); }, {345 code: 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL'346 });347});348test('-- by itself is not a positional', () => {349 const args = ['--foo', '--'];350 const options = { foo: { type: 'boolean' } };351 const result = parseArgs({ args, options });352 const expected = { values: { __proto__: null, foo: true },353 positionals: [] };354 assert.deepStrictEqual(result, expected);355});356test('string option used as boolean', () => {357 const args = ['--foo'];358 const options = { foo: { type: 'string' } };359 assert.throws(() => { parseArgs({ args, options }); }, {360 code: 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'361 });362});363test('boolean option used with value', () => {364 const args = ['--foo=bar'];365 const options = { foo: { type: 'boolean' } };366 assert.throws(() => { parseArgs({ args, options }); }, {367 code: 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'368 });369});370test('invalid short option length', () => {371 const args = [];372 const options = { foo: { short: 'fo', type: 'boolean' } };373 assert.throws(() => { parseArgs({ args, options }); }, {374 code: 'ERR_INVALID_ARG_VALUE'375 });376});377test('null prototype: when no options then values.toString is undefined', () => {378 const result = parseArgs({ args: [] });379 assert.strictEqual(result.values.toString, undefined);380});381test('null prototype: when --toString then values.toString is true', () => {382 const args = ['--toString'];383 const options = { toString: { type: 'boolean' } };384 const expectedResult = { values: { __proto__: null, toString: true }, positionals: [] };385 const result = parseArgs({ args, options });386 assert.deepStrictEqual(result, expectedResult);387});388const candidateGreedyOptions = [389 '',390 '-',391 '--',392 'abc',393 '123',394 '-s',395 '--foo',396];397candidateGreedyOptions.forEach((value) => {398 test(`greedy: when short option with value '${value}' then eaten`, () => {399 const args = ['-w', value];400 const options = { with: { type: 'string', short: 'w' } };401 const expectedResult = { values: { __proto__: null, with: value }, positionals: [] };402 const result = parseArgs({ args, options, strict: false });403 assert.deepStrictEqual(result, expectedResult);404 });405 test(`greedy: when long option with value '${value}' then eaten`, () => {406 const args = ['--with', value];407 const options = { with: { type: 'string', short: 'w' } };408 const expectedResult = { values: { __proto__: null, with: value }, positionals: [] };409 const result = parseArgs({ args, options, strict: false });410 assert.deepStrictEqual(result, expectedResult);411 });412});413test('strict: when candidate option value is plain text then does not throw', () => {414 const args = ['--with', 'abc'];415 const options = { with: { type: 'string' } };416 const expectedResult = { values: { __proto__: null, with: 'abc' }, positionals: [] };417 const result = parseArgs({ args, options, strict: true });418 assert.deepStrictEqual(result, expectedResult);419});420test("strict: when candidate option value is '-' then does not throw", () => {421 const args = ['--with', '-'];422 const options = { with: { type: 'string' } };423 const expectedResult = { values: { __proto__: null, with: '-' }, positionals: [] };424 const result = parseArgs({ args, options, strict: true });425 assert.deepStrictEqual(result, expectedResult);426});427test("strict: when candidate option value is '--' then throws", () => {428 const args = ['--with', '--'];429 const options = { with: { type: 'string' } };430 assert.throws(() => {431 parseArgs({ args, options });432 }, {433 code: 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'434 });435});436test('strict: when candidate option value is short option then throws', () => {437 const args = ['--with', '-a'];438 const options = { with: { type: 'string' } };439 assert.throws(() => {440 parseArgs({ args, options });441 }, {442 code: 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'443 });444});445test('strict: when candidate option value is short option digit then throws', () => {446 const args = ['--with', '-1'];447 const options = { with: { type: 'string' } };448 assert.throws(() => {449 parseArgs({ args, options });450 }, {451 code: 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'452 });453});454test('strict: when candidate option value is long option then throws', () => {455 const args = ['--with', '--foo'];456 const options = { with: { type: 'string' } };457 assert.throws(() => {458 parseArgs({ args, options });459 }, {460 code: 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'461 });462});463test('strict: when short option and suspect value then throws with short option in error message', () => {464 const args = ['-w', '--foo'];465 const options = { with: { type: 'string', short: 'w' } };466 assert.throws(() => {467 parseArgs({ args, options });468 }, /for '-w'/469 );470});471test('strict: when long option and suspect value then throws with long option in error message', () => {472 const args = ['--with', '--foo'];473 const options = { with: { type: 'string' } };474 assert.throws(() => {475 parseArgs({ args, options });476 }, /for '--with'/477 );478});479test('strict: when short option and suspect value then throws with whole expected message', () => {480 const args = ['-w', '--foo'];481 const options = { with: { type: 'string', short: 'w' } };482 try {483 parseArgs({ args, options });484 } catch (err) {485 console.info(err.message);486 }487 assert.throws(() => {488 parseArgs({ args, options });489 }, /To specify an option argument starting with a dash use '--with=-XYZ' or '-w-XYZ'/490 );491});492test('strict: when long option and suspect value then throws with whole expected message', () => {493 const args = ['--with', '--foo'];494 const options = { with: { type: 'string', short: 'w' } };495 assert.throws(() => {496 parseArgs({ args, options });497 }, /To specify an option argument starting with a dash use '--with=-XYZ'/498 );...
create_wanlink.py
Source:create_wanlink.py
1#!/usr/bin/python32# Create and modify WAN Links Using LANforge JSON AP : http://www.candelatech.com/cookbook.php?vol=cli&book=JSON:+Managing+WANlinks+using+JSON+and+Python3# Written by Candela Technologies Inc.4# Updated by: Erin Grimes5"""6sample command:7./test_wanlink.py --name my_wanlink4 --latency_A 20 --latency_B 69 --rate 1000 --jitter_A 53 --jitter_B 73 --jitter_freq 6 --drop_A 12 --drop_B 118"""9import sys10import urllib11import importlib12if sys.version_info[0] != 3:13 print("This script requires Python 3")14 exit(1)15import os16from time import sleep17from urllib import error18import pprint19import argparse20 21sys.path.append(os.path.join(os.path.abspath(__file__ + "../../../")))22LFRequest = importlib.import_module("py-json.LANforge.LFRequest")23LFUtils = importlib.import_module("py-json.LANforge.LFUtils")24lfcli_base = importlib.import_module("py-json.LANforge.lfcli_base")25LFCliBase = lfcli_base.LFCliBase26j_printer = pprint.PrettyPrinter(indent=2)27# todo: this needs to change28resource_id = 129def main(args):30 base_url = 'http://'+args['host']+':8080'31 print(base_url)32 json_post = ""33 json_response = ""34 num_wanlinks = -135 # see if there are old wanlinks to remove36 lf_r = LFRequest.LFRequest(base_url+"/wl/list")37 print(lf_r.get_as_json())38 # remove old wanlinks39 if num_wanlinks > 0:40 lf_r = LFRequest.LFRequest(base_url+"/cli-json/rm_cx")41 lf_r.addPostData({42 'test_mgr': 'all',43 'cx_name': args['name']44 })45 lf_r.jsonPost()46 sleep(0.05)47 try:48 json_response = lf_r.getAsJson()49 LFUtils.debug_printer.pprint(json_response)50 for key, value in json_response.items():51 if isinstance(value, dict) and "_links" in value:52 num_wanlinks = 153 except urllib.error.HTTPError as error:54 print("Error code %s" % error.code)55 lf_r = LFRequest.LFRequest(base_url+"/cli-json/rm_endp")56 lf_r.addPostData({57 'endp_name': args['name']+"-A"58 })59 lf_r.jsonPost()60 sleep(0.05)61 lf_r = LFRequest.LFRequest(base_url+"/cli-json/rm_endp")62 lf_r.addPostData({63 'endp_name': args['name']+"-B"64 })65 lf_r.jsonPost()66 sleep(0.05)67 # create wanlink endpoint A68 lf_r = LFRequest.LFRequest(base_url+"/cli-json/add_wl_endp")69 lf_r.addPostData({70 'alias': args['name']+"-A",71 'shelf': 1,72 'resource': '1',73 'port': args['port_A'],74 'latency': args['latency_A'],75 'max_rate': args['rate_A'],76 })77 lf_r.jsonPost()78 sleep(0.05)79 # create wanlink endpoint B80 lf_r = LFRequest.LFRequest(base_url+"/cli-json/add_wl_endp")81 lf_r.addPostData({82 'alias': args['name']+"-B",83 'shelf': 1,84 'resource': '1',85 'port': args['port_B'],86 'latency': args['latency_B'],87 'max_rate': args['rate_B'],88 })89 lf_r.jsonPost()90 sleep(0.05)91 # create cx92 lf_r = LFRequest.LFRequest(base_url+"/cli-json/add_cx")93 lf_r.addPostData({94 'alias': args['name'],95 'test_mgr': 'default_tm',96 'tx_endp': args['name']+"-A",97 'rx_endp': args['name']+"-B",98 })99 lf_r.jsonPost()100 sleep(0.05)101 # modify wanlink endpoint A102 lf_r = LFRequest.LFRequest(base_url+"/cli-json/set_wanlink_info")103 lf_r.addPostData({104 'name': args['name']+"-A",105 'max_jitter': args['jitter_A'],106 'jitter_freq': args['jitter_freq_A'],107 'drop_freq': args['drop_A']108 })109 lf_r.jsonPost()110 sleep(0.05)111 # modify wanlink endpoint B112 lf_r = LFRequest.LFRequest(base_url+"/cli-json/set_wanlink_info")113 lf_r.addPostData({114 'name': args['name']+"-B",115 'max_jitter': args['jitter_B'],116 'jitter_freq': args['jitter_freq_B'],117 'drop_freq': args['drop_B']118 })119 lf_r.jsonPost()120 sleep(0.05)121 # start wanlink once we see it122 seen = 0123 while seen < 1:124 sleep(1)125 lf_r = LFRequest.LFRequest(base_url+"/wl/"+args['name']+"?fields=name,state,_links")126 try:127 json_response = lf_r.getAsJson()128 if json_response is None:129 continue130 LFUtils.debug_printer.pprint(json_response)131 for key, value in json_response.items():132 if isinstance(value, dict):133 if "_links" in value:134 if value["name"] == args['name']:135 seen = 1136 else:137 pass138 # else:139 # print(" name was not wl_eg1")140 # else:141 # print("value lacks _links")142 # else:143 # print("value not a dict")144 except urllib.error.HTTPError as error:145 print("Error code %s " % error.code)146 continue147 # print("starting wanlink:")148 # # print("the latency is {laten}".format(laten=latency))149 # lf_r = LFRequest.LFRequest(base_url+"/cli-json/set_cx_state")150 # lf_r.addPostData({151 # 'test_mgr': 'all',152 # 'cx_name': args['name'],153 # 'cx_state': 'RUNNING'154 # })155 # lf_r.jsonPost()156 running = 0157 while running < 1:158 sleep(1)159 lf_r = LFRequest.LFRequest(base_url+"/wl/"+args['name']+"?fields=name,state,_links")160 try:161 json_response = lf_r.getAsJson()162 if json_response is None:163 continue164 for key, value in json_response.items():165 if isinstance(value, dict):166 if "_links" in value:167 if value["name"] == args['name']:168 if value["state"].startswith("Run"):169 LFUtils.debug_printer.pprint(json_response)170 running = 1171 except urllib.error.HTTPError as error:172 print("Error code %s" % error.code)173 continue174 print("Wanlink is running")175 # # stop wanlink176 # lf_r = LFRequest.LFRequest(base_url+"/cli-json/set_cx_state")177 # lf_r.addPostData({178 # 'test_mgr': 'all',179 # 'cx_name': args['name'],180 # 'cx_state': 'STOPPED'181 # })182 # lf_r.jsonPost()183 # running = 1184 # while (running > 0):185 # sleep(1)186 # lf_r = LFRequest.LFRequest(base_url+"/wl/"+args['name']+"?fields=name,eid,state,_links")187 # LFUtils.debug_printer.pprint(json_response)188 # try:189 # json_response = lf_r.getAsJson()190 # if (json_response is None):191 # continue192 # for key, value in json_response.items():193 # if (isinstance(value, dict)):194 # if ("_links" in value):195 # if (value["name"] == args['name']):196 # if (value["state"].startswith("Stop")):197 # LFUtils.debug_printer.pprint(json_response)198 # running = 0199 # except urllib.error.HTTPError as error:200 # print("Error code "+error.code)201 # continue202 # print("Wanlink is stopped.")203 # print("Wanlink info:")204 # lf_r = LFRequest.LFRequest(base_url+"/wl/wl_eg1")205 # json_response = lf_r.getAsJson()206 # LFUtils.debug_printer.pprint(json_response)207 # lf_r = LFRequest.LFRequest(base_url+"/wl_ep/wl_eg1-A")208 # json_response = lf_r.getAsJson()209 # LFUtils.debug_printer.pprint(json_response)210 # lf_r = LFRequest.LFRequest(base_url+"/wl_ep/wl_eg1-B")211 # json_response = lf_r.getAsJson()212 # LFUtils.debug_printer.pprint(json_response)213# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -214if __name__ == '__main__':215 parser = LFCliBase.create_basic_argparse(216 prog='create_wanlink.py',217 formatter_class=argparse.RawTextHelpFormatter)218 for group in parser._action_groups:219 if group.title == "required arguments":220 required_args = group221 break222 optional_args = None223 for group in parser._action_groups:224 if group.title == "optional arguments":225 optional_args = group226 break227 if optional_args is not None:228 optional_args.add_argument('--host', help='The resource IP address', default="localhost")229 optional_args.add_argument('--port_A', help='Endpoint A', default="eth1")230 optional_args.add_argument('--port_B', help='Endpoint B', default="eth2")231 optional_args.add_argument('--name', help='The name of the wanlink', default="wl_eg1")232 optional_args.add_argument('--rate', help='The maximum rate of transfer at both endpoints (bits/s)', default=1000000)233 optional_args.add_argument('--rate_A', help='The max rate of transfer at endpoint A (bits/s)', default=None)234 optional_args.add_argument('--rate_B', help='The maximum rate of transfer (bits/s)', default=None)235 optional_args.add_argument('--latency', help='The delay of both ports', default=20)236 optional_args.add_argument('--latency_A', help='The delay of port A', default=None)237 optional_args.add_argument('--latency_B', help='The delay of port B', default=None)238 optional_args.add_argument('--jitter', help='The max jitter of both ports (ms)', default=None)239 optional_args.add_argument('--jitter_A', help='The max jitter of port A (ms)', default=None)240 optional_args.add_argument('--jitter_B', help='The max jitter of port B (ms)', default=None)241 optional_args.add_argument('--jitter_freq', help='The jitter frequency of both ports (%%)', default=None)242 optional_args.add_argument('--jitter_freq_A', help='The jitter frequency of port A (%%)', default=None)243 optional_args.add_argument('--jitter_freq_B', help='The jitter frequency of port B (%%)', default=None)244 optional_args.add_argument('--drop', help='The drop frequency of both ports (%%)', default=None)245 optional_args.add_argument('--drop_A', help='The drop frequency of port A (%%)', default=None)246 optional_args.add_argument('--drop_B', help='The drop frequency of port B (%%)', default=None)247 # todo: packet loss A and B248 # todo: jitter A and B249 for group in parser._action_groups:250 if group.title == "optional arguments":251 optional_args = group252 break253 parseargs = parser.parse_args()254 args = {255 "host": parseargs.mgr,256 "port": parseargs.mgr_port,257 "name": parseargs.name,258 "port_A": parseargs.port_A,259 "port_B": parseargs.port_B,260 "latency": parseargs.latency,261 "latency_A": (parseargs.latency_A if parseargs.latency_A is not None else parseargs.latency),262 "latency_B": (parseargs.latency_B if parseargs.latency_B is not None else parseargs.latency),263 "rate": parseargs.rate,264 "rate_A": (parseargs.rate_A if parseargs.rate_A is not None else parseargs.rate),265 "rate_B": (parseargs.rate_B if parseargs.rate_B is not None else parseargs.rate),266 "jitter": parseargs.jitter,267 "jitter_A": (parseargs.jitter_A if parseargs.jitter_A is not None else parseargs.jitter),268 "jitter_B": (parseargs.jitter_B if parseargs.jitter_B is not None else parseargs.jitter),269 "jitter_freq": parseargs.jitter,270 "jitter_freq_A": (parseargs.jitter_freq_A if parseargs.jitter_freq_A is not None else parseargs.jitter_freq),271 "jitter_freq_B": (parseargs.jitter_freq_B if parseargs.jitter_freq_B is not None else parseargs.jitter_freq),272 "drop": parseargs.drop,273 "drop_A": (parseargs.drop_A if parseargs.drop_A is not None else parseargs.drop),274 "drop_B": (parseargs.drop_B if parseargs.drop_B is not None else parseargs.drop),275 }...
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!!