How to use testDir method in storybook-root

Best JavaScript code snippet using storybook-root

test.js

Source:test.js Github

copy

Full Screen

1'use strict';2/*3Setup testing environment4=========================5*/6//Testing modules7var test = require('tidytest');8//Module to test9var dir = require('../index.js');10var path = require('tidypath');11var fs = require('tidyfs');12/*13Tests14=====15*/16test('mkTree()', function(assert){ 17 assert.plan(3);18 19 dir.mkTree('./test/testdir/helloworld')20 .then(function(){21 assert.ok(true, 'folder created');22 })23 .catch(function(err){24 assert.fail(err);25 });26 27 dir.mkTree([28 './test/testdir/helloworld',29 './test/testdir/helloworld/foo/',30 './test/testdir/helloworld/foo/bar',31 './test/testdir/helloworld/foo/hello', 32 './test/testdir/helloworld/foo/world',33 ])34 .then(function(){35 assert.ok(true, 'multiple folders created');36 })37 .catch(function(err){38 assert.fail(err);39 });40 41 dir.mkTree([]).then(function(){42 assert.ok(true, 'Empty array of trees to make');43 })44 .catch(function(err){45 assert.fail(err);46 });47});48test('mkFile()', function(assert){ 49 assert.plan(7);50 51 dir.mkFile('./test/testdir/hello.txt', 'world','utf8')52 .then(function(){53 assert.ok(true, 'Make file in existing folder');54 })55 .catch(function(err){56 assert.fail(err);57 });;58 59 dir.mkFile('./test/testdir/foo/hello.txt', 'world','utf8')60 .then(function(){61 assert.ok(true, 'Make file in new folder');62 })63 .catch(function(err){64 assert.fail(err);65 }); 66 67 dir.mkFile({68 path : './test/testdir/foo/world.js', 69 content : 'hello',70 options : 'utf8'71 })72 .then(function(){73 assert.ok(true, 'Make file via object param');74 })75 .catch(function(err){76 assert.fail(err);77 }); 78 79 dir.mkFile([{80 path : './test/testdir/foo/foo.txt', 81 content : 'bar',82 options : 'utf8'83 },84 {85 path : './test/testdir/foo/bar.txt', 86 content : 'foo',87 options : 'utf8'88 },89 {90 path : './test/testdir/bar/hello.txt', 91 content : 'foo',92 options : 'utf8'93 },94 {95 path : './test/testdir/foobar/hello.txt', 96 content : 'foo',97 options : 'utf8'98 }99 ,100 {101 path : './test/testdir/hello/world.txt', 102 content : 'foo',103 options : 'utf8'104 }])105 .then(function(){106 assert.ok(true, 'Make multiple files via array of objects');107 })108 .catch(function(err){109 assert.fail(err);110 }); 111 dir.mkFile({112 path : './test/testdir/foo/helloworld.txt', 113 content : 'foo bar'114 }, 115 'utf8')116 .then(function(){117 assert.ok(true, 'Default for common option');118 })119 .catch(function(err){120 assert.fail(err);121 }); 122 123 dir.mkFile([{124 path : './test/testdir/foo/foobar.txt', 125 content : 'hello world'126 }])127 .then(function(){128 assert.ok(true, 'Default for no option argument');129 })130 .catch(function(err){131 assert.fail(err);132 }); 133 134 dir.mkFile([]).then(function(){135 assert.ok(true, 'Empty array of files to make');136 })137 .catch(function(err){138 assert.fail(err);139 });140});141test('listTree()', function(assert){142 assert.plan(3);143 144 var testTree = { 145 files: 146 [ 147 './test/testdir/hello.txt',148 './test/testdir/bar/hello.txt',149 './test/testdir/foo/bar.txt',150 './test/testdir/foo/foo.txt',151 './test/testdir/foo/foobar.txt',152 './test/testdir/foo/hello.txt',153 './test/testdir/foo/helloworld.txt',154 './test/testdir/foo/world.js', 155 './test/testdir/foobar/hello.txt',156 './test/testdir/hello/world.txt'157 ],158 dirs: 159 [160 './test/testdir/bar',161 './test/testdir/foo',162 './test/testdir/foobar',163 './test/testdir/hello',164 './test/testdir/helloworld',165 './test/testdir/helloworld/foo',166 './test/testdir/helloworld/foo/bar',167 './test/testdir/helloworld/foo/hello', 168 './test/testdir/helloworld/foo/world' 169 ] 170 }171 172 dir.listTree('./test/testdir')173 .then(function(tree){174 tree.files = path.filter(tree.files, path.dotfile, false);175 assert.deepEqual(tree, testTree,176 'All files and folders are listed')177 })178 .catch(function(err){179 assert.fail(err);180 }); 181 182 dir.listTree('./test/testdir', 183 function(param){184 if (path.dotfile(param)){return false;}185 else{return true;}186 })187 .then(function(tree){188 assert.deepEqual(tree, testTree,189 'List a filtered tree')190 })191 .catch(function(err){192 assert.fail(err);193 }); 194 195 dir.listTree(['./test/testdir/helloworld',196 './test/testdir/foo'])197 .then(function(tree){198 assert.deepEqual(tree, 199 {200 files : testTree.files.slice(2,8),201 dirs : testTree.dirs.slice(5)202 },203 'List multiple trees')204 })205 .catch(function(err){206 assert.fail(err);207 }); 208});209test('readFile()', function(assert){210 assert.plan(8);211 dir.readFile('./test/testdir/hello.txt', 'utf8')212 .then(function(file){213 assert.equal(file.content, 'world',214 'Basic read file');215 })216 .catch(function(err){217 assert.fail(err);218 }); 219 220 dir.readFile({221 path : './test/testdir/hello.txt', 222 options : 'utf8'223 })224 .then(function(file){225 assert.equal(file.content, 'world',226 'File read via object');227 })228 .catch(function(err){229 assert.fail(err);230 }); 231 232 dir.readFile([233 './test/testdir/hello.txt',234 './test/testdir/foo/world.js'235 ],236 'utf8')237 .then(function(files){238 assert.deepEqual(files, 239 [{240 path : './test/testdir/hello.txt', 241 options : 'utf8',242 content : 'world'243 },244 {245 path : './test/testdir/foo/world.js', 246 options : 'utf8',247 content : 'hello'248 }],249 'File read via array');250 })251 .catch(function(err){252 assert.fail(err);253 }); 254 255 dir.readFile([256 {257 path : './test/testdir/hello.txt', 258 options : 'utf8'259 },260 {261 path : './test/testdir/foo/world.js', 262 options : 'utf8' 263 }], 264 'buffer')265 .then(function(files){266 assert.deepEqual(files, 267 [{268 path : './test/testdir/hello.txt', 269 options : 'utf8',270 content : 'world'271 },272 {273 path : './test/testdir/foo/world.js', 274 options : 'utf8',275 content : 'hello'276 }],277 'File read via array of objects');278 })279 .catch(function(err){280 assert.fail(err);281 }); 282 283 dir.readFile(['./test/testdir/hello.txt',284 './test/testdir/foo/world.js'])285 .then(function(files){286 assert.deepEqual(files, 287 [{288 path : './test/testdir/hello.txt', 289 options : 'utf8',290 content : 'world'291 },292 {293 path : './test/testdir/foo/world.js', 294 options : 'utf8',295 content : 'hello'296 }],297 'Default options');298 })299 .catch(function(err){300 assert.fail(err);301 }); 302 303 dir.readFile(['./test/testdir/hello.txt',304 './test/testdir/foo/world.js'],305 'utf8',306 '.js')307 .then(function(files){308 assert.deepEqual(files, 309 [{310 path : './test/testdir/foo/world.js', 311 options : 'utf8',312 content : 'hello'313 }],314 'Read filtered files with options');315 })316 .catch(function(err){317 assert.fail(err);318 }); 319 320 dir.readFile(['./test/testdir/hello.txt',321 './test/testdir/foo/world.js'],322 '.js')323 .then(function(files){324 assert.deepEqual(files, 325 [{326 path : './test/testdir/foo/world.js', 327 options : 'utf8',328 content : 'hello'329 }],330 'Read filtered files without options');331 })332 .catch(function(err){333 assert.fail(err);334 });335 336 dir.readFile([]).then(function(){337 assert.ok(true, 'Empty array of files to read');338 })339 .catch(function(err){340 assert.fail(err);341 });342});343test('readTree', function(assert){344 assert.plan(8);345 dir.readTree('./test/testdir/foo/', 'utf8')346 .then(function(tree){347 assert.deepEqual(tree,348 {349 files: [{350 path : './test/testdir/foo/bar.txt',351 content : 'foo',352 options : 'utf8'353 },354 {355 path : './test/testdir/foo/foo.txt',356 content : 'bar',357 options : 'utf8'358 },359 {360 path : './test/testdir/foo/foobar.txt',361 content : 'hello world',362 options : 'utf8'363 },364 {365 path : './test/testdir/foo/hello.txt',366 content : 'world',367 options : 'utf8'368 },369 {370 path : './test/testdir/foo/helloworld.txt',371 content : 'foo bar',372 options : 'utf8'373 },374 {375 path : './test/testdir/foo/world.js',376 content : 'hello',377 options : 'utf8'378 }],379 dirs : []380 },381 'Basic read tree');382 })383 .catch(function(err){384 assert.fail(err);385 }); 386 dir.readTree({path:'./test/testdir/foo/'}, 'utf8')387 .then(function(tree){388 assert.deepEqual(tree,389 {390 files: [{391 path : './test/testdir/foo/bar.txt',392 content : 'foo',393 options : 'utf8'394 },395 {396 path : './test/testdir/foo/foo.txt',397 content : 'bar',398 options : 'utf8'399 },400 {401 path : './test/testdir/foo/foobar.txt',402 content : 'hello world',403 options : 'utf8'404 },405 {406 path : './test/testdir/foo/hello.txt',407 content : 'world',408 options : 'utf8'409 },410 {411 path : './test/testdir/foo/helloworld.txt',412 content : 'foo bar',413 options : 'utf8'414 },415 {416 path : './test/testdir/foo/world.js',417 content : 'hello',418 options : 'utf8'419 }],420 dirs : []421 },422 'Read tree via object');423 })424 .catch(function(err){425 assert.fail(err);426 }); 427 428 dir.readTree(['./test/testdir/foo/'])429 .then(function(tree){430 assert.deepEqual(tree,431 [{432 files: [{433 path : './test/testdir/foo/bar.txt',434 content : 'foo',435 options : 'utf8'436 },437 {438 path : './test/testdir/foo/foo.txt',439 content : 'bar',440 options : 'utf8'441 },442 {443 path : './test/testdir/foo/foobar.txt',444 content : 'hello world',445 options : 'utf8'446 },447 {448 path : './test/testdir/foo/hello.txt',449 content : 'world',450 options : 'utf8'451 },452 {453 path : './test/testdir/foo/helloworld.txt',454 content : 'foo bar',455 options : 'utf8'456 },457 {458 path : './test/testdir/foo/world.js',459 content : 'hello',460 options : 'utf8'461 }],462 dirs : []463 }],464 'Read tree via array');465 })466 .catch(function(err){467 assert.fail(err);468 }); 469 470 dir.readTree([{path:'./test/testdir/foo/', options: 'uft8'}], 'buffer')471 .then(function(tree){472 assert.deepEqual(tree,473 [{474 files: [{475 path : './test/testdir/foo/bar.txt',476 content : 'foo',477 options : 'utf8'478 },479 {480 path : './test/testdir/foo/foo.txt',481 content : 'bar',482 options : 'utf8'483 },484 {485 path : './test/testdir/foo/foobar.txt',486 content : 'hello world',487 options : 'utf8'488 },489 {490 path : './test/testdir/foo/hello.txt',491 content : 'world',492 options : 'utf8'493 },494 {495 path : './test/testdir/foo/helloworld.txt',496 content : 'foo bar',497 options : 'utf8'498 },499 {500 path : './test/testdir/foo/world.js',501 content : 'hello',502 options : 'utf8'503 }],504 dirs : []505 }],506 'Read tree via array of objects');507 })508 .catch(function(err){509 assert.fail(err);510 }); 511 512 dir.readTree('./test/testdir/bar/')513 .then(function(tree){514 assert.deepEqual(tree,515 {516 files: [{517 path : './test/testdir/bar/hello.txt',518 content : 'foo',519 options : 'utf8'520 }],521 dirs : []522 },523 'Default options');524 })525 .catch(function(err){526 assert.fail(err);527 }); 528 529 dir.readTree('./test/testdir/foo/', 'utf8', '.js')530 .then(function(tree){531 assert.deepEqual(tree,532 {533 files: [{534 path : './test/testdir/foo/world.js',535 content : 'hello',536 options : 'utf8'537 }],538 dirs : []539 },540 'Read tree filtered with options');541 })542 .catch(function(err){543 assert.fail(err);544 }); 545 546 dir.readTree('./test/testdir/foo/', '.js')547 .then(function(tree){548 assert.deepEqual(tree,549 {550 files: [{551 path : './test/testdir/foo/world.js',552 content : 'hello',553 options : 'utf8'554 }],555 dirs : []556 },557 'Read tree filtered without options');558 })559 .catch(function(err){560 assert.fail(err);561 }); 562 563 dir.readTree([]).then(function(){564 assert.ok(true, 'Empty array of trees to read');565 })566 .catch(function(err){567 assert.fail(err);568 });569});570test('rmFile()', function(assert){571 assert.plan(3);572 573 dir.rmFile('./test/testdir/hello.txt')574 .then(function(){575 return fs.access('./test/testdir/hello.txt');576 })577 .then(function(){578 assert.fail('./test/testdir/hello.txt not removed');579 })580 .catch(function(err){581 if (err.errno === -2){ //err.code 'ENOENT'582 assert.ok(true, 'File removed');583 }584 else{585 assert.fail(err);586 }587 });588 589 dir.rmFile([590 './test/testdir/foo/bar.txt',591 './test/testdir/foo/foo.txt'592 ])593 .then(function(){594 return Promise.all([595 fs.access('./test/testdir/foo/bar.txt'),596 fs.access('./test/testdir/foo/foo.txt')597 ]); 598 599 })600 .then(function(){601 assert.fail('Multiple files not removed');602 })603 .catch(function(err){604 if (err.errno === -2){ //err.code 'ENOENT'605 assert.ok(true, 'Multiple files removed');606 }607 else{608 assert.fail(err);609 }610 });611 612 dir.rmFile([]).then(function(){613 assert.ok(true, 'Empty array of files to remove');614 })615 .catch(function(err){616 assert.fail(err);617 });618});619test('rmDir()', function(assert){620 assert.plan(2);621 622 dir.rmDir('./test/testdir/helloworld/foo/bar')623 .then(function(){624 return fs.access('./test/testdir/helloworld/foo/bar');625 })626 .then(function(){627 assert.fail('Dir not removed');628 })629 .catch(function(err){630 if (err.errno === -2){ //err.code 'ENOENT'631 assert.ok(true, 'Dir removed');632 }633 else{634 assert.fail(err);635 }636 })637 638 639 dir.rmDir([640 './test/testdir/helloworld/foo/hello',641 './test/testdir/helloworld/foo/world',642 ])643 .then(function(){644 return Promise.all([645 fs.access('./test/testdir/helloworld/foo/hello'),646 fs.access('./test/testdir/helloworld/foo/world')647 ]); 648 649 })650 .then(function(){651 assert.fail('Multiple dirs not removed');652 })653 .catch(function(err){654 if (err.errno === -2){ //err.code 'ENOENT'655 assert.ok(true, 'Multiple dirs removed');656 }657 else{658 assert.fail(err);659 }660 });661});662test('emptyTree()', function(assert){663 assert.plan(3);664 665 dir.emptyTree('./test/testdir/helloworld/')666 .then(function(){667 return dir.listTree('./test/testdir/helloworld/');668 })669 .then(function(tree){670 if (tree.dirs.length === 0){671 assert.ok(true, 'Emptied tree');672 }673 else{674 throw new Error('emptyTree() failed');675 }676 })677 .catch(function(err){678 assert.fail(err);679 });680 681 dir.emptyTree([682 './test/testdir/foobar',683 './test/testdir/hello'684 ])685 .then(function(){686 return Promise.all([687 dir.listTree('./test/testdir/foobar'),688 dir.listTree('./test/testdir/hello')689 ]); 690 691 })692 .then(function(tree){693 if (tree[0].dirs.length === 0694 && tree[1].dirs.length === 0){695 assert.ok(true, 'Multiple trees emptied');696 }697 else{698 throw new Error('Did not empty multiple trees');699 }700 })701 .catch(function(err){702 assert.fail(err);703 });704 705 dir.emptyTree([]).then(function(){706 assert.ok(true, 'Empty array of trees to empty');707 })708 .catch(function(err){709 assert.fail(err);710 }); 711});712 713test('rmTree()', function(assert){714 assert.plan(3);715 716 dir.rmTree('./test/testdir/foobar')717 .then(function(){718 return fs.access('./test/testdir/foobar');719 })720 .then(function(){721 assert.fail('Tree not removed');722 })723 .catch(function(err){724 if (err.errno === -2){ //err.code 'ENOENT'725 assert.ok(true, 'Tree removed');726 }727 else{728 assert.fail(err);729 }730 })731 //Start second test732 .then(function(){733 return dir.rmTree([734 './test/testdir/',735 './test/testdir/hello'736 ]); 737 })738 .then(function(){739 return Promise.all([740 fs.access('./test/testdir/'),741 fs.access('./test/testdir/hello')742 ]); 743 744 })745 .then(function(){746 assert.fail('Multiple trees not removed');747 })748 .catch(function(err){749 if (err.errno === -2){ //err.code 'ENOENT'750 assert.ok(true, 'Multiple trees removed');751 }752 else{753 assert.fail(err);754 }755 });756 757 758 dir.rmTree([]).then(function(){759 assert.ok(true, 'Empty array of trees to remove');760 })761 .catch(function(err){762 assert.fail(err);763 });764});765/*766================================767TEST SHORTHAND VERSION OF MODULE768================================769*/770test('mk() as mkTree() substitute', function(assert){ 771 assert.plan(3);772 773 dir.mk('./test/testdir/helloworld')774 .then(function(){775 assert.ok(true, 'folder created');776 })777 .catch(function(err){778 assert.fail(err);779 });780 781 dir.mk([782 './test/testdir/helloworld',783 './test/testdir/helloworld/foo/',784 './test/testdir/helloworld/foo/bar',785 './test/testdir/helloworld/foo/hello', 786 './test/testdir/helloworld/foo/world',787 ])788 .then(function(){789 assert.ok(true, 'multiple folders created');790 })791 .catch(function(err){792 assert.fail(err);793 });794 795 dir.mk([]).then(function(){796 assert.ok(true, 'Empty array of trees to make');797 })798 .catch(function(err){799 assert.fail(err);800 });801});802test('mk() as mkFile substitute', function(assert){ 803 assert.plan(7);804 805 dir.mk('./test/testdir/hello.txt', 'world','utf8')806 .then(function(){807 assert.ok(true, 'Make file in existing folder');808 })809 .catch(function(err){810 assert.fail(err);811 });;812 813 dir.mk('./test/testdir/foo/hello.txt', 'world','utf8')814 .then(function(){815 assert.ok(true, 'Make file in new folder');816 })817 .catch(function(err){818 assert.fail(err);819 }); 820 821 dir.mk({822 path : './test/testdir/foo/world.js', 823 content : 'hello',824 options : 'utf8'825 })826 .then(function(){827 assert.ok(true, 'Make file via object param');828 })829 .catch(function(err){830 assert.fail(err);831 }); 832 833 dir.mk([{834 path : './test/testdir/foo/foo.txt', 835 content : 'bar',836 options : 'utf8'837 },838 {839 path : './test/testdir/foo/bar.txt', 840 content : 'foo',841 options : 'utf8'842 },843 {844 path : './test/testdir/bar/hello.txt', 845 content : 'foo',846 options : 'utf8'847 },848 {849 path : './test/testdir/foobar/hello.txt', 850 content : 'foo',851 options : 'utf8'852 }853 ,854 {855 path : './test/testdir/hello/world.txt', 856 content : 'foo',857 options : 'utf8'858 }])859 .then(function(){860 assert.ok(true, 'Make multiple files via array of objects');861 })862 .catch(function(err){863 assert.fail(err);864 }); 865 dir.mk({866 path : './test/testdir/foo/helloworld.txt', 867 content : 'foo bar'868 }, 869 'utf8')870 .then(function(){871 assert.ok(true, 'Default for common option');872 })873 .catch(function(err){874 assert.fail(err);875 }); 876 877 dir.mk([{878 path : './test/testdir/foo/foobar.txt', 879 content : 'hello world'880 }])881 .then(function(){882 assert.ok(true, 'Default for no option argument');883 })884 .catch(function(err){885 assert.fail(err);886 }); 887 888 dir.mk([]).then(function(){889 assert.ok(true, 'Empty array of files to make');890 })891 .catch(function(err){892 assert.fail(err);893 });894});895test('list() as listTree() synonym', function(assert){896 assert.plan(3);897 898 var testTree = { 899 files: 900 [ 901 './test/testdir/hello.txt',902 './test/testdir/bar/hello.txt',903 './test/testdir/foo/bar.txt',904 './test/testdir/foo/foo.txt',905 './test/testdir/foo/foobar.txt',906 './test/testdir/foo/hello.txt',907 './test/testdir/foo/helloworld.txt',908 './test/testdir/foo/world.js', 909 './test/testdir/foobar/hello.txt',910 './test/testdir/hello/world.txt'911 ],912 dirs: 913 [914 './test/testdir/bar',915 './test/testdir/foo',916 './test/testdir/foobar',917 './test/testdir/hello',918 './test/testdir/helloworld',919 './test/testdir/helloworld/foo',920 './test/testdir/helloworld/foo/bar',921 './test/testdir/helloworld/foo/hello', 922 './test/testdir/helloworld/foo/world' 923 ] 924 }925 926 dir.list('./test/testdir')927 .then(function(tree){928 tree.files = path.filter(tree.files, path.dotfile, false);929 assert.deepEqual(tree, testTree,930 'All files and folders are listed')931 })932 .catch(function(err){933 assert.fail(err);934 }); 935 936 dir.list('./test/testdir', 937 function(param){938 if (path.dotfile(param)){return false;}939 else{return true;}940 })941 .then(function(tree){942 assert.deepEqual(tree, testTree,943 'List a filtered tree')944 })945 .catch(function(err){946 assert.fail(err);947 }); 948 949 dir.list(['./test/testdir/helloworld',950 './test/testdir/foo'])951 .then(function(tree){952 assert.deepEqual(tree, 953 {954 files : testTree.files.slice(2,8),955 dirs : testTree.dirs.slice(5)956 },957 'List multiple trees')958 })959 .catch(function(err){960 assert.fail(err);961 }); 962});963test('ls() as listTree() synonym', function(assert){964 assert.plan(3);965 966 var testTree = { 967 files: 968 [ 969 './test/testdir/hello.txt',970 './test/testdir/bar/hello.txt',971 './test/testdir/foo/bar.txt',972 './test/testdir/foo/foo.txt',973 './test/testdir/foo/foobar.txt',974 './test/testdir/foo/hello.txt',975 './test/testdir/foo/helloworld.txt',976 './test/testdir/foo/world.js', 977 './test/testdir/foobar/hello.txt',978 './test/testdir/hello/world.txt'979 ],980 dirs: 981 [982 './test/testdir/bar',983 './test/testdir/foo',984 './test/testdir/foobar',985 './test/testdir/hello',986 './test/testdir/helloworld',987 './test/testdir/helloworld/foo',988 './test/testdir/helloworld/foo/bar',989 './test/testdir/helloworld/foo/hello', 990 './test/testdir/helloworld/foo/world' 991 ] 992 }993 994 dir.ls('./test/testdir')995 .then(function(tree){996 tree.files = path.filter(tree.files, path.dotfile, false);997 assert.deepEqual(tree, testTree,998 'All files and folders are listed')999 })1000 .catch(function(err){1001 assert.fail(err);1002 }); 1003 1004 dir.ls('./test/testdir', 1005 function(param){1006 if (path.dotfile(param)){return false;}1007 else{return true;}1008 })1009 .then(function(tree){1010 assert.deepEqual(tree, testTree,1011 'List a filtered tree')1012 })1013 .catch(function(err){1014 assert.fail(err);1015 }); 1016 1017 dir.ls(['./test/testdir/helloworld',1018 './test/testdir/foo'])1019 .then(function(tree){1020 assert.deepEqual(tree, 1021 {1022 files : testTree.files.slice(2,8),1023 dirs : testTree.dirs.slice(5)1024 },1025 'List multiple trees')1026 })1027 .catch(function(err){1028 assert.fail(err);1029 }); 1030});1031test('read() as readFile() substitute', function(assert){1032 assert.plan(8);1033 dir.read('./test/testdir/hello.txt', 'utf8')1034 .then(function(file){1035 assert.equal(file.content, 'world',1036 'Basic read file');1037 })1038 .catch(function(err){1039 assert.fail(err);1040 }); 1041 1042 dir.read({1043 path : './test/testdir/hello.txt', 1044 options : 'utf8'1045 })1046 .then(function(file){1047 assert.equal(file.content, 'world',1048 'File read via object');1049 })1050 .catch(function(err){1051 assert.fail(err);1052 }); 1053 1054 dir.read([1055 './test/testdir/hello.txt',1056 './test/testdir/foo/world.js'1057 ],1058 'utf8')1059 .then(function(files){1060 assert.deepEqual(files, 1061 [{1062 path : './test/testdir/hello.txt', 1063 options : 'utf8',1064 content : 'world'1065 },1066 {1067 path : './test/testdir/foo/world.js', 1068 options : 'utf8',1069 content : 'hello'1070 }],1071 'File read via array');1072 })1073 .catch(function(err){1074 assert.fail(err);1075 }); 1076 1077 dir.read([1078 {1079 path : './test/testdir/hello.txt', 1080 options : 'utf8'1081 },1082 {1083 path : './test/testdir/foo/world.js', 1084 options : 'utf8' 1085 }], 1086 'buffer')1087 .then(function(files){1088 assert.deepEqual(files, 1089 [{1090 path : './test/testdir/hello.txt', 1091 options : 'utf8',1092 content : 'world'1093 },1094 {1095 path : './test/testdir/foo/world.js', 1096 options : 'utf8',1097 content : 'hello'1098 }],1099 'File read via array of objects');1100 })1101 .catch(function(err){1102 assert.fail(err);1103 }); 1104 1105 dir.read(['./test/testdir/hello.txt',1106 './test/testdir/foo/world.js'])1107 .then(function(files){1108 assert.deepEqual(files, 1109 [{1110 path : './test/testdir/hello.txt', 1111 options : 'utf8',1112 content : 'world'1113 },1114 {1115 path : './test/testdir/foo/world.js', 1116 options : 'utf8',1117 content : 'hello'1118 }],1119 'Default options');1120 })1121 .catch(function(err){1122 assert.fail(err);1123 }); 1124 1125 dir.read(['./test/testdir/hello.txt',1126 './test/testdir/foo/world.js'],1127 'utf8',1128 '.js')1129 .then(function(files){1130 assert.deepEqual(files, 1131 [{1132 path : './test/testdir/foo/world.js', 1133 options : 'utf8',1134 content : 'hello'1135 }],1136 'Read filtered files with options');1137 })1138 .catch(function(err){1139 assert.fail(err);1140 }); 1141 1142 dir.read(['./test/testdir/hello.txt',1143 './test/testdir/foo/world.js'],1144 '.js')1145 .then(function(files){1146 assert.deepEqual(files, 1147 [{1148 path : './test/testdir/foo/world.js', 1149 options : 'utf8',1150 content : 'hello'1151 }],1152 'Read filtered files without options');1153 })1154 .catch(function(err){1155 assert.fail(err);1156 });1157 1158 dir.read([]).then(function(){1159 assert.ok(true, 'Empty array of files to read');1160 })1161 .catch(function(err){1162 assert.fail(err);1163 });1164});1165test('read() as readTree() substitute', function(assert){1166 assert.plan(8);1167 dir.read('./test/testdir/foo/', 'utf8')1168 .then(function(tree){1169 assert.deepEqual(tree,1170 {1171 files: [{1172 path : './test/testdir/foo/bar.txt',1173 content : 'foo',1174 options : 'utf8'1175 },1176 {1177 path : './test/testdir/foo/foo.txt',1178 content : 'bar',1179 options : 'utf8'1180 },1181 {1182 path : './test/testdir/foo/foobar.txt',1183 content : 'hello world',1184 options : 'utf8'1185 },1186 {1187 path : './test/testdir/foo/hello.txt',1188 content : 'world',1189 options : 'utf8'1190 },1191 {1192 path : './test/testdir/foo/helloworld.txt',1193 content : 'foo bar',1194 options : 'utf8'1195 },1196 {1197 path : './test/testdir/foo/world.js',1198 content : 'hello',1199 options : 'utf8'1200 }],1201 dirs : []1202 },1203 'Basic read tree');1204 })1205 .catch(function(err){1206 assert.fail(err);1207 }); 1208 dir.read({path:'./test/testdir/foo/'}, 'utf8')1209 .then(function(tree){1210 assert.deepEqual(tree,1211 {1212 files: [{1213 path : './test/testdir/foo/bar.txt',1214 content : 'foo',1215 options : 'utf8'1216 },1217 {1218 path : './test/testdir/foo/foo.txt',1219 content : 'bar',1220 options : 'utf8'1221 },1222 {1223 path : './test/testdir/foo/foobar.txt',1224 content : 'hello world',1225 options : 'utf8'1226 },1227 {1228 path : './test/testdir/foo/hello.txt',1229 content : 'world',1230 options : 'utf8'1231 },1232 {1233 path : './test/testdir/foo/helloworld.txt',1234 content : 'foo bar',1235 options : 'utf8'1236 },1237 {1238 path : './test/testdir/foo/world.js',1239 content : 'hello',1240 options : 'utf8'1241 }],1242 dirs : []1243 },1244 'Read tree via object');1245 })1246 .catch(function(err){1247 assert.fail(err);1248 }); 1249 1250 dir.read(['./test/testdir/foo/'])1251 .then(function(tree){1252 assert.deepEqual(tree,1253 [{1254 files: [{1255 path : './test/testdir/foo/bar.txt',1256 content : 'foo',1257 options : 'utf8'1258 },1259 {1260 path : './test/testdir/foo/foo.txt',1261 content : 'bar',1262 options : 'utf8'1263 },1264 {1265 path : './test/testdir/foo/foobar.txt',1266 content : 'hello world',1267 options : 'utf8'1268 },1269 {1270 path : './test/testdir/foo/hello.txt',1271 content : 'world',1272 options : 'utf8'1273 },1274 {1275 path : './test/testdir/foo/helloworld.txt',1276 content : 'foo bar',1277 options : 'utf8'1278 },1279 {1280 path : './test/testdir/foo/world.js',1281 content : 'hello',1282 options : 'utf8'1283 }],1284 dirs : []1285 }],1286 'Read tree via array');1287 })1288 .catch(function(err){1289 assert.fail(err);1290 }); 1291 1292 dir.read([{path:'./test/testdir/foo/', options: 'uft8'}], 'buffer')1293 .then(function(tree){1294 assert.deepEqual(tree,1295 [{1296 files: [{1297 path : './test/testdir/foo/bar.txt',1298 content : 'foo',1299 options : 'utf8'1300 },1301 {1302 path : './test/testdir/foo/foo.txt',1303 content : 'bar',1304 options : 'utf8'1305 },1306 {1307 path : './test/testdir/foo/foobar.txt',1308 content : 'hello world',1309 options : 'utf8'1310 },1311 {1312 path : './test/testdir/foo/hello.txt',1313 content : 'world',1314 options : 'utf8'1315 },1316 {1317 path : './test/testdir/foo/helloworld.txt',1318 content : 'foo bar',1319 options : 'utf8'1320 },1321 {1322 path : './test/testdir/foo/world.js',1323 content : 'hello',1324 options : 'utf8'1325 }],1326 dirs : []1327 }],1328 'Read tree via array of objects');1329 })1330 .catch(function(err){1331 assert.fail(err);1332 }); 1333 1334 dir.read('./test/testdir/bar/')1335 .then(function(tree){1336 assert.deepEqual(tree,1337 {1338 files: [{1339 path : './test/testdir/bar/hello.txt',1340 content : 'foo',1341 options : 'utf8'1342 }],1343 dirs : []1344 },1345 'Default options');1346 })1347 .catch(function(err){1348 assert.fail(err);1349 }); 1350 1351 dir.read('./test/testdir/foo/', 'utf8', '.js')1352 .then(function(tree){1353 assert.deepEqual(tree,1354 {1355 files: [{1356 path : './test/testdir/foo/world.js',1357 content : 'hello',1358 options : 'utf8'1359 }],1360 dirs : []1361 },1362 'Read tree filtered with options');1363 })1364 .catch(function(err){1365 assert.fail(err);1366 }); 1367 1368 dir.read('./test/testdir/foo/', '.js')1369 .then(function(tree){1370 assert.deepEqual(tree,1371 {1372 files: [{1373 path : './test/testdir/foo/world.js',1374 content : 'hello',1375 options : 'utf8'1376 }],1377 dirs : []1378 },1379 'Read tree filtered without options');1380 })1381 .catch(function(err){1382 assert.fail(err);1383 }); 1384 1385 dir.read([]).then(function(){1386 assert.ok(true, 'Empty array of trees to read');1387 })1388 .catch(function(err){1389 assert.fail(err);1390 });1391});1392test('rm() as rmFile() substitute', function(assert){1393 assert.plan(3);1394 1395 dir.rm('./test/testdir/hello.txt')1396 .then(function(){1397 return fs.access('./test/testdir/hello.txt');1398 })1399 .then(function(){1400 assert.fail('./test/testdir/hello.txt not removed');1401 })1402 .catch(function(err){1403 if (err.errno === -2){ //err.code 'ENOENT'1404 assert.ok(true, 'File removed');1405 }1406 else{1407 assert.fail(err);1408 }1409 });1410 1411 dir.rm([1412 './test/testdir/foo/bar.txt',1413 './test/testdir/foo/foo.txt'1414 ])1415 .then(function(){1416 return Promise.all([1417 fs.access('./test/testdir/foo/bar.txt'),1418 fs.access('./test/testdir/foo/foo.txt')1419 ]); 1420 1421 })1422 .then(function(){1423 assert.fail('Multiple files not removed');1424 })1425 .catch(function(err){1426 if (err.errno === -2){ //err.code 'ENOENT'1427 assert.ok(true, 'Multiple files removed');1428 }1429 else{1430 assert.fail(err);1431 }1432 });1433 1434 dir.rm([]).then(function(){1435 assert.ok(true, 'Empty array of files to remove');1436 })1437 .catch(function(err){1438 assert.fail(err);1439 });1440});1441test('empty() as emptyTree() synonym', function(assert){1442 assert.plan(3);1443 1444 dir.empty('./test/testdir/helloworld/')1445 .then(function(){1446 return dir.listTree('./test/testdir/helloworld/');1447 })1448 .then(function(tree){1449 if (tree.dirs.length === 0){1450 assert.ok(true, 'Emptied tree');1451 }1452 else{1453 throw new Error('emptyTree() failed');1454 }1455 })1456 .catch(function(err){1457 assert.fail(err);1458 });1459 1460 dir.empty([1461 './test/testdir/foobar',1462 './test/testdir/hello'1463 ])1464 .then(function(){1465 return Promise.all([1466 dir.listTree('./test/testdir/foobar'),1467 dir.listTree('./test/testdir/hello')1468 ]); 1469 1470 })1471 .then(function(tree){1472 if (tree[0].dirs.length === 01473 && tree[1].dirs.length === 0){1474 assert.ok(true, 'Multiple trees emptied');1475 }1476 else{1477 throw new Error('Did not empty multiple trees');1478 }1479 })1480 .catch(function(err){1481 assert.fail(err);1482 });1483 1484 dir.empty([]).then(function(){1485 assert.ok(true, 'Empty array of trees to empty');1486 })1487 .catch(function(err){1488 assert.fail(err);1489 }); 1490});1491 1492test('rm() as rmTree() substitute', function(assert){1493 assert.plan(3);1494 1495 dir.rm('./test/testdir/foobar')1496 .then(function(){1497 return fs.access('./test/testdir/foobar');1498 })1499 .then(function(){1500 assert.fail('Tree not removed');1501 })1502 .catch(function(err){1503 if (err.errno === -2){ //err.code 'ENOENT'1504 assert.ok(true, 'Tree removed');1505 }1506 else{1507 assert.fail(err);1508 }1509 })1510 //Start second test1511 .then(function(){1512 return dir.rm([1513 './test/testdir/',1514 './test/testdir/hello'1515 ]); 1516 })1517 .then(function(){1518 return Promise.all([1519 fs.access('./test/testdir/'),1520 fs.access('./test/testdir/hello')1521 ]); 1522 1523 })1524 .then(function(){1525 assert.fail('Multiple trees not removed');1526 })1527 .catch(function(err){1528 if (err.errno === -2){ //err.code 'ENOENT'1529 assert.ok(true, 'Multiple trees removed');1530 }1531 else{1532 assert.fail(err);1533 }1534 });1535 1536 1537 dir.rm([]).then(function(){1538 assert.ok(true, 'Empty array of trees to remove');1539 })1540 .catch(function(err){1541 assert.fail(err);1542 });...

Full Screen

Full Screen

test_skipping.py

Source:test_skipping.py Github

copy

Full Screen

1import pytest2import sys3from _pytest.skipping import MarkEvaluator, folded_skips, pytest_runtest_setup4from _pytest.runner import runtestprotocol5class TestEvaluator:6 def test_no_marker(self, testdir):7 item = testdir.getitem("def test_func(): pass")8 evalskipif = MarkEvaluator(item, 'skipif')9 assert not evalskipif10 assert not evalskipif.istrue()11 def test_marked_no_args(self, testdir):12 item = testdir.getitem("""13 import pytest14 @pytest.mark.xyz15 def test_func():16 pass17 """)18 ev = MarkEvaluator(item, 'xyz')19 assert ev20 assert ev.istrue()21 expl = ev.getexplanation()22 assert expl == ""23 assert not ev.get("run", False)24 def test_marked_one_arg(self, testdir):25 item = testdir.getitem("""26 import pytest27 @pytest.mark.xyz("hasattr(os, 'sep')")28 def test_func():29 pass30 """)31 ev = MarkEvaluator(item, 'xyz')32 assert ev33 assert ev.istrue()34 expl = ev.getexplanation()35 assert expl == "condition: hasattr(os, 'sep')"36 @pytest.mark.skipif('sys.version_info[0] >= 3')37 def test_marked_one_arg_unicode(self, testdir):38 item = testdir.getitem("""39 import pytest40 @pytest.mark.xyz(u"hasattr(os, 'sep')")41 def test_func():42 pass43 """)44 ev = MarkEvaluator(item, 'xyz')45 assert ev46 assert ev.istrue()47 expl = ev.getexplanation()48 assert expl == "condition: hasattr(os, 'sep')"49 def test_marked_one_arg_with_reason(self, testdir):50 item = testdir.getitem("""51 import pytest52 @pytest.mark.xyz("hasattr(os, 'sep')", attr=2, reason="hello world")53 def test_func():54 pass55 """)56 ev = MarkEvaluator(item, 'xyz')57 assert ev58 assert ev.istrue()59 expl = ev.getexplanation()60 assert expl == "hello world"61 assert ev.get("attr") == 262 def test_marked_one_arg_twice(self, testdir):63 lines = [64 '''@pytest.mark.skipif("not hasattr(os, 'murks')")''',65 '''@pytest.mark.skipif("hasattr(os, 'murks')")'''66 ]67 for i in range(0, 2):68 item = testdir.getitem("""69 import pytest70 %s71 %s72 def test_func():73 pass74 """ % (lines[i], lines[(i+1) %2]))75 ev = MarkEvaluator(item, 'skipif')76 assert ev77 assert ev.istrue()78 expl = ev.getexplanation()79 assert expl == "condition: not hasattr(os, 'murks')"80 def test_marked_one_arg_twice2(self, testdir):81 item = testdir.getitem("""82 import pytest83 @pytest.mark.skipif("hasattr(os, 'murks')")84 @pytest.mark.skipif("not hasattr(os, 'murks')")85 def test_func():86 pass87 """)88 ev = MarkEvaluator(item, 'skipif')89 assert ev90 assert ev.istrue()91 expl = ev.getexplanation()92 assert expl == "condition: not hasattr(os, 'murks')"93 def test_marked_skip_with_not_string(self, testdir):94 item = testdir.getitem("""95 import pytest96 @pytest.mark.skipif(False)97 def test_func():98 pass99 """)100 ev = MarkEvaluator(item, 'skipif')101 exc = pytest.raises(pytest.fail.Exception, ev.istrue)102 assert """Failed: you need to specify reason=STRING when using booleans as conditions.""" in exc.value.msg103 def test_skipif_class(self, testdir):104 item, = testdir.getitems("""105 import pytest106 class TestClass:107 pytestmark = pytest.mark.skipif("config._hackxyz")108 def test_func(self):109 pass110 """)111 item.config._hackxyz = 3112 ev = MarkEvaluator(item, 'skipif')113 assert ev.istrue()114 expl = ev.getexplanation()115 assert expl == "condition: config._hackxyz"116class TestXFail:117 @pytest.mark.parametrize('strict', [True, False])118 def test_xfail_simple(self, testdir, strict):119 item = testdir.getitem("""120 import pytest121 @pytest.mark.xfail(strict=%s)122 def test_func():123 assert 0124 """ % strict)125 reports = runtestprotocol(item, log=False)126 assert len(reports) == 3127 callreport = reports[1]128 assert callreport.skipped129 assert callreport.wasxfail == ""130 def test_xfail_xpassed(self, testdir):131 item = testdir.getitem("""132 import pytest133 @pytest.mark.xfail134 def test_func():135 assert 1136 """)137 reports = runtestprotocol(item, log=False)138 assert len(reports) == 3139 callreport = reports[1]140 assert callreport.failed141 assert callreport.wasxfail == ""142 def test_xfail_run_anyway(self, testdir):143 testdir.makepyfile("""144 import pytest145 @pytest.mark.xfail146 def test_func():147 assert 0148 def test_func2():149 pytest.xfail("hello")150 """)151 result = testdir.runpytest("--runxfail")152 result.stdout.fnmatch_lines([153 "*def test_func():*",154 "*assert 0*",155 "*1 failed*1 pass*",156 ])157 def test_xfail_evalfalse_but_fails(self, testdir):158 item = testdir.getitem("""159 import pytest160 @pytest.mark.xfail('False')161 def test_func():162 assert 0163 """)164 reports = runtestprotocol(item, log=False)165 callreport = reports[1]166 assert callreport.failed167 assert not hasattr(callreport, "wasxfail")168 assert 'xfail' in callreport.keywords169 def test_xfail_not_report_default(self, testdir):170 p = testdir.makepyfile(test_one="""171 import pytest172 @pytest.mark.xfail173 def test_this():174 assert 0175 """)176 testdir.runpytest(p, '-v')177 #result.stdout.fnmatch_lines([178 # "*HINT*use*-r*"179 #])180 def test_xfail_not_run_xfail_reporting(self, testdir):181 p = testdir.makepyfile(test_one="""182 import pytest183 @pytest.mark.xfail(run=False, reason="noway")184 def test_this():185 assert 0186 @pytest.mark.xfail("True", run=False)187 def test_this_true():188 assert 0189 @pytest.mark.xfail("False", run=False, reason="huh")190 def test_this_false():191 assert 1192 """)193 result = testdir.runpytest(p, '--report=xfailed', )194 result.stdout.fnmatch_lines([195 "*test_one*test_this*",196 "*NOTRUN*noway",197 "*test_one*test_this_true*",198 "*NOTRUN*condition:*True*",199 "*1 passed*",200 ])201 def test_xfail_not_run_no_setup_run(self, testdir):202 p = testdir.makepyfile(test_one="""203 import pytest204 @pytest.mark.xfail(run=False, reason="hello")205 def test_this():206 assert 0207 def setup_module(mod):208 raise ValueError(42)209 """)210 result = testdir.runpytest(p, '--report=xfailed', )211 result.stdout.fnmatch_lines([212 "*test_one*test_this*",213 "*NOTRUN*hello",214 "*1 xfailed*",215 ])216 def test_xfail_xpass(self, testdir):217 p = testdir.makepyfile(test_one="""218 import pytest219 @pytest.mark.xfail220 def test_that():221 assert 1222 """)223 result = testdir.runpytest(p, '-rX')224 result.stdout.fnmatch_lines([225 "*XPASS*test_that*",226 "*1 xpassed*"227 ])228 assert result.ret == 0229 def test_xfail_imperative(self, testdir):230 p = testdir.makepyfile("""231 import pytest232 def test_this():233 pytest.xfail("hello")234 """)235 result = testdir.runpytest(p)236 result.stdout.fnmatch_lines([237 "*1 xfailed*",238 ])239 result = testdir.runpytest(p, "-rx")240 result.stdout.fnmatch_lines([241 "*XFAIL*test_this*",242 "*reason:*hello*",243 ])244 result = testdir.runpytest(p, "--runxfail")245 result.stdout.fnmatch_lines("*1 pass*")246 def test_xfail_imperative_in_setup_function(self, testdir):247 p = testdir.makepyfile("""248 import pytest249 def setup_function(function):250 pytest.xfail("hello")251 def test_this():252 assert 0253 """)254 result = testdir.runpytest(p)255 result.stdout.fnmatch_lines([256 "*1 xfailed*",257 ])258 result = testdir.runpytest(p, "-rx")259 result.stdout.fnmatch_lines([260 "*XFAIL*test_this*",261 "*reason:*hello*",262 ])263 result = testdir.runpytest(p, "--runxfail")264 result.stdout.fnmatch_lines("""265 *def test_this*266 *1 fail*267 """)268 def xtest_dynamic_xfail_set_during_setup(self, testdir):269 p = testdir.makepyfile("""270 import pytest271 def setup_function(function):272 pytest.mark.xfail(function)273 def test_this():274 assert 0275 def test_that():276 assert 1277 """)278 result = testdir.runpytest(p, '-rxX')279 result.stdout.fnmatch_lines([280 "*XFAIL*test_this*",281 "*XPASS*test_that*",282 ])283 def test_dynamic_xfail_no_run(self, testdir):284 p = testdir.makepyfile("""285 import pytest286 def pytest_funcarg__arg(request):287 request.applymarker(pytest.mark.xfail(run=False))288 def test_this(arg):289 assert 0290 """)291 result = testdir.runpytest(p, '-rxX')292 result.stdout.fnmatch_lines([293 "*XFAIL*test_this*",294 "*NOTRUN*",295 ])296 def test_dynamic_xfail_set_during_funcarg_setup(self, testdir):297 p = testdir.makepyfile("""298 import pytest299 def pytest_funcarg__arg(request):300 request.applymarker(pytest.mark.xfail)301 def test_this2(arg):302 assert 0303 """)304 result = testdir.runpytest(p)305 result.stdout.fnmatch_lines([306 "*1 xfailed*",307 ])308 @pytest.mark.parametrize('expected, actual, matchline',309 [('TypeError', 'TypeError', "*1 xfailed*"),310 ('(AttributeError, TypeError)', 'TypeError', "*1 xfailed*"),311 ('TypeError', 'IndexError', "*1 failed*"),312 ('(AttributeError, TypeError)', 'IndexError', "*1 failed*"),313 ])314 def test_xfail_raises(self, expected, actual, matchline, testdir):315 p = testdir.makepyfile("""316 import pytest317 @pytest.mark.xfail(raises=%s)318 def test_raises():319 raise %s()320 """ % (expected, actual))321 result = testdir.runpytest(p)322 result.stdout.fnmatch_lines([323 matchline,324 ])325 def test_strict_sanity(self, testdir):326 """sanity check for xfail(strict=True): a failing test should behave327 exactly like a normal xfail.328 """329 p = testdir.makepyfile("""330 import pytest331 @pytest.mark.xfail(reason='unsupported feature', strict=True)332 def test_foo():333 assert 0334 """)335 result = testdir.runpytest(p, '-rxX')336 result.stdout.fnmatch_lines([337 '*XFAIL*',338 '*unsupported feature*',339 ])340 assert result.ret == 0341 @pytest.mark.parametrize('strict', [True, False])342 def test_strict_xfail(self, testdir, strict):343 p = testdir.makepyfile("""344 import pytest345 @pytest.mark.xfail(reason='unsupported feature', strict=%s)346 def test_foo():347 with open('foo_executed', 'w'): pass # make sure test executes348 """ % strict)349 result = testdir.runpytest(p, '-rxX')350 if strict:351 result.stdout.fnmatch_lines([352 '*test_foo*',353 '*XPASS(strict)*unsupported feature*',354 ])355 else:356 result.stdout.fnmatch_lines([357 '*test_strict_xfail*',358 'XPASS test_strict_xfail.py::test_foo unsupported feature',359 ])360 assert result.ret == (1 if strict else 0)361 assert testdir.tmpdir.join('foo_executed').isfile()362 @pytest.mark.parametrize('strict', [True, False])363 def test_strict_xfail_condition(self, testdir, strict):364 p = testdir.makepyfile("""365 import pytest366 @pytest.mark.xfail(False, reason='unsupported feature', strict=%s)367 def test_foo():368 pass369 """ % strict)370 result = testdir.runpytest(p, '-rxX')371 result.stdout.fnmatch_lines('*1 passed*')372 assert result.ret == 0373 @pytest.mark.parametrize('strict_val', ['true', 'false'])374 def test_strict_xfail_default_from_file(self, testdir, strict_val):375 testdir.makeini('''376 [pytest]377 xfail_strict = %s378 ''' % strict_val)379 p = testdir.makepyfile("""380 import pytest381 @pytest.mark.xfail(reason='unsupported feature')382 def test_foo():383 pass384 """)385 result = testdir.runpytest(p, '-rxX')386 strict = strict_val == 'true'387 result.stdout.fnmatch_lines('*1 failed*' if strict else '*1 xpassed*')388 assert result.ret == (1 if strict else 0)389class TestXFailwithSetupTeardown:390 def test_failing_setup_issue9(self, testdir):391 testdir.makepyfile("""392 import pytest393 def setup_function(func):394 assert 0395 @pytest.mark.xfail396 def test_func():397 pass398 """)399 result = testdir.runpytest()400 result.stdout.fnmatch_lines([401 "*1 xfail*",402 ])403 def test_failing_teardown_issue9(self, testdir):404 testdir.makepyfile("""405 import pytest406 def teardown_function(func):407 assert 0408 @pytest.mark.xfail409 def test_func():410 pass411 """)412 result = testdir.runpytest()413 result.stdout.fnmatch_lines([414 "*1 xfail*",415 ])416class TestSkip:417 def test_skip_class(self, testdir):418 testdir.makepyfile("""419 import pytest420 @pytest.mark.skip421 class TestSomething(object):422 def test_foo(self):423 pass424 def test_bar(self):425 pass426 def test_baz():427 pass428 """)429 rec = testdir.inline_run()430 rec.assertoutcome(skipped=2, passed=1)431 def test_skips_on_false_string(self, testdir):432 testdir.makepyfile("""433 import pytest434 @pytest.mark.skip('False')435 def test_foo():436 pass437 """)438 rec = testdir.inline_run()439 rec.assertoutcome(skipped=1)440 def test_arg_as_reason(self, testdir):441 testdir.makepyfile("""442 import pytest443 @pytest.mark.skip('testing stuff')444 def test_bar():445 pass446 """)447 result = testdir.runpytest('-rs')448 result.stdout.fnmatch_lines([449 "*testing stuff*",450 "*1 skipped*",451 ])452 def test_skip_no_reason(self, testdir):453 testdir.makepyfile("""454 import pytest455 @pytest.mark.skip456 def test_foo():457 pass458 """)459 result = testdir.runpytest('-rs')460 result.stdout.fnmatch_lines([461 "*unconditional skip*",462 "*1 skipped*",463 ])464 def test_skip_with_reason(self, testdir):465 testdir.makepyfile("""466 import pytest467 @pytest.mark.skip(reason="for lolz")468 def test_bar():469 pass470 """)471 result = testdir.runpytest('-rs')472 result.stdout.fnmatch_lines([473 "*for lolz*",474 "*1 skipped*",475 ])476 def test_only_skips_marked_test(self, testdir):477 testdir.makepyfile("""478 import pytest479 @pytest.mark.skip480 def test_foo():481 pass482 @pytest.mark.skip(reason="nothing in particular")483 def test_bar():484 pass485 def test_baz():486 assert True487 """)488 result = testdir.runpytest('-rs')489 result.stdout.fnmatch_lines([490 "*nothing in particular*",491 "*1 passed*2 skipped*",492 ])493class TestSkipif:494 def test_skipif_conditional(self, testdir):495 item = testdir.getitem("""496 import pytest497 @pytest.mark.skipif("hasattr(os, 'sep')")498 def test_func():499 pass500 """) # noqa501 x = pytest.raises(pytest.skip.Exception, lambda:502 pytest_runtest_setup(item))503 assert x.value.msg == "condition: hasattr(os, 'sep')"504 @pytest.mark.parametrize('params', [505 '"hasattr(sys, \'platform\')"',506 'True, reason="invalid platform"',507 ])508 def test_skipif_reporting(self, testdir, params):509 p = testdir.makepyfile(test_foo="""510 import pytest511 @pytest.mark.skipif(%(params)s)512 def test_that():513 assert 0514 """ % dict(params=params))515 result = testdir.runpytest(p, '-s', '-rs')516 result.stdout.fnmatch_lines([517 "*SKIP*1*test_foo.py*platform*",518 "*1 skipped*"519 ])520 assert result.ret == 0521 @pytest.mark.parametrize('marker, msg1, msg2', [522 ('skipif', 'SKIP', 'skipped'),523 ('xfail', 'XPASS', 'xpassed'),524 ])525 def test_skipif_reporting_multiple(self, testdir, marker, msg1, msg2):526 testdir.makepyfile(test_foo="""527 import pytest528 @pytest.mark.{marker}(False, reason='first_condition')529 @pytest.mark.{marker}(True, reason='second_condition')530 def test_foobar():531 assert 1532 """.format(marker=marker))533 result = testdir.runpytest('-s', '-rsxX')534 result.stdout.fnmatch_lines([535 "*{msg1}*test_foo.py*second_condition*".format(msg1=msg1),536 "*1 {msg2}*".format(msg2=msg2),537 ])538 assert result.ret == 0539def test_skip_not_report_default(testdir):540 p = testdir.makepyfile(test_one="""541 import pytest542 def test_this():543 pytest.skip("hello")544 """)545 result = testdir.runpytest(p, '-v')546 result.stdout.fnmatch_lines([547 #"*HINT*use*-r*",548 "*1 skipped*",549 ])550def test_skipif_class(testdir):551 p = testdir.makepyfile("""552 import pytest553 class TestClass:554 pytestmark = pytest.mark.skipif("True")555 def test_that(self):556 assert 0557 def test_though(self):558 assert 0559 """)560 result = testdir.runpytest(p)561 result.stdout.fnmatch_lines([562 "*2 skipped*"563 ])564def test_skip_reasons_folding():565 path = 'xyz'566 lineno = 3567 message = "justso"568 longrepr = (path, lineno, message)569 class X:570 pass571 ev1 = X()572 ev1.when = "execute"573 ev1.skipped = True574 ev1.longrepr = longrepr575 ev2 = X()576 ev2.longrepr = longrepr577 ev2.skipped = True578 l = folded_skips([ev1, ev2])579 assert len(l) == 1580 num, fspath, lineno, reason = l[0]581 assert num == 2582 assert fspath == path583 assert lineno == lineno584 assert reason == message585def test_skipped_reasons_functional(testdir):586 testdir.makepyfile(587 test_one="""588 from conftest import doskip589 def setup_function(func):590 doskip()591 def test_func():592 pass593 class TestClass:594 def test_method(self):595 doskip()596 """,597 test_two = """598 from conftest import doskip599 doskip()600 """,601 conftest = """602 import pytest603 def doskip():604 pytest.skip('test')605 """606 )607 result = testdir.runpytest('--report=skipped')608 result.stdout.fnmatch_lines([609 "*SKIP*3*conftest.py:3: test",610 ])611 assert result.ret == 0612def test_reportchars(testdir):613 testdir.makepyfile("""614 import pytest615 def test_1():616 assert 0617 @pytest.mark.xfail618 def test_2():619 assert 0620 @pytest.mark.xfail621 def test_3():622 pass623 def test_4():624 pytest.skip("four")625 """)626 result = testdir.runpytest("-rfxXs")627 result.stdout.fnmatch_lines([628 "FAIL*test_1*",629 "XFAIL*test_2*",630 "XPASS*test_3*",631 "SKIP*four*",632 ])633def test_reportchars_error(testdir):634 testdir.makepyfile(635 conftest="""636 def pytest_runtest_teardown():637 assert 0638 """,639 test_simple="""640 def test_foo():641 pass642 """)643 result = testdir.runpytest('-rE')644 result.stdout.fnmatch_lines([645 'ERROR*test_foo*',646 ])647def test_reportchars_all(testdir):648 testdir.makepyfile("""649 import pytest650 def test_1():651 assert 0652 @pytest.mark.xfail653 def test_2():654 assert 0655 @pytest.mark.xfail656 def test_3():657 pass658 def test_4():659 pytest.skip("four")660 """)661 result = testdir.runpytest("-ra")662 result.stdout.fnmatch_lines([663 "FAIL*test_1*",664 "SKIP*four*",665 "XFAIL*test_2*",666 "XPASS*test_3*",667 ])668def test_reportchars_all_error(testdir):669 testdir.makepyfile(670 conftest="""671 def pytest_runtest_teardown():672 assert 0673 """,674 test_simple="""675 def test_foo():676 pass677 """)678 result = testdir.runpytest('-ra')679 result.stdout.fnmatch_lines([680 'ERROR*test_foo*',681 ])682@pytest.mark.xfail("hasattr(sys, 'pypy_version_info')")683def test_errors_in_xfail_skip_expressions(testdir):684 testdir.makepyfile("""685 import pytest686 @pytest.mark.skipif("asd")687 def test_nameerror():688 pass689 @pytest.mark.xfail("syntax error")690 def test_syntax():691 pass692 def test_func():693 pass694 """)695 result = testdir.runpytest()696 markline = " ^"697 if sys.platform.startswith("java"):698 # XXX report this to java699 markline = "*" + markline[8:]700 result.stdout.fnmatch_lines([701 "*ERROR*test_nameerror*",702 "*evaluating*skipif*expression*",703 "*asd*",704 "*ERROR*test_syntax*",705 "*evaluating*xfail*expression*",706 " syntax error",707 markline,708 "SyntaxError: invalid syntax",709 "*1 pass*2 error*",710 ])711def test_xfail_skipif_with_globals(testdir):712 testdir.makepyfile("""713 import pytest714 x = 3715 @pytest.mark.skipif("x == 3")716 def test_skip1():717 pass718 @pytest.mark.xfail("x == 3")719 def test_boolean():720 assert 0721 """)722 result = testdir.runpytest("-rsx")723 result.stdout.fnmatch_lines([724 "*SKIP*x == 3*",725 "*XFAIL*test_boolean*",726 "*x == 3*",727 ])728def test_direct_gives_error(testdir):729 testdir.makepyfile("""730 import pytest731 @pytest.mark.skipif(True)732 def test_skip1():733 pass734 """)735 result = testdir.runpytest()736 result.stdout.fnmatch_lines([737 "*1 error*",738 ])739def test_default_markers(testdir):740 result = testdir.runpytest("--markers")741 result.stdout.fnmatch_lines([742 "*skipif(*condition)*skip*",743 "*xfail(*condition, reason=None, run=True, raises=None)*expected failure*",744 ])745def test_xfail_test_setup_exception(testdir):746 testdir.makeconftest("""747 def pytest_runtest_setup():748 0 / 0749 """)750 p = testdir.makepyfile("""751 import pytest752 @pytest.mark.xfail753 def test_func():754 assert 0755 """)756 result = testdir.runpytest(p)757 assert result.ret == 0758 assert 'xfailed' in result.stdout.str()759 assert 'xpassed' not in result.stdout.str()760def test_imperativeskip_on_xfail_test(testdir):761 testdir.makepyfile("""762 import pytest763 @pytest.mark.xfail764 def test_that_fails():765 assert 0766 @pytest.mark.skipif("True")767 def test_hello():768 pass769 """)770 testdir.makeconftest("""771 import pytest772 def pytest_runtest_setup(item):773 pytest.skip("abc")774 """)775 result = testdir.runpytest("-rsxX")776 result.stdout.fnmatch_lines_random("""777 *SKIP*abc*778 *SKIP*condition: True*779 *2 skipped*780 """)781class TestBooleanCondition:782 def test_skipif(self, testdir):783 testdir.makepyfile("""784 import pytest785 @pytest.mark.skipif(True, reason="True123")786 def test_func1():787 pass788 @pytest.mark.skipif(False, reason="True123")789 def test_func2():790 pass791 """)792 result = testdir.runpytest()793 result.stdout.fnmatch_lines("""794 *1 passed*1 skipped*795 """)796 def test_skipif_noreason(self, testdir):797 testdir.makepyfile("""798 import pytest799 @pytest.mark.skipif(True)800 def test_func():801 pass802 """)803 result = testdir.runpytest("-rs")804 result.stdout.fnmatch_lines("""805 *1 error*806 """)807 def test_xfail(self, testdir):808 testdir.makepyfile("""809 import pytest810 @pytest.mark.xfail(True, reason="True123")811 def test_func():812 assert 0813 """)814 result = testdir.runpytest("-rxs")815 result.stdout.fnmatch_lines("""816 *XFAIL*817 *True123*818 *1 xfail*819 """)820def test_xfail_item(testdir):821 # Ensure pytest.xfail works with non-Python Item822 testdir.makeconftest("""823 import pytest824 class MyItem(pytest.Item):825 nodeid = 'foo'826 def runtest(self):827 pytest.xfail("Expected Failure")828 def pytest_collect_file(path, parent):829 return MyItem("foo", parent)830 """)831 result = testdir.inline_run()832 passed, skipped, failed = result.listoutcomes()833 assert not failed834 xfailed = [r for r in skipped if hasattr(r, 'wasxfail')]...

Full Screen

Full Screen

acceptance_test.py

Source:acceptance_test.py Github

copy

Full Screen

1import sys2import _pytest._code3import py4import pytest5from _pytest.main import EXIT_NOTESTSCOLLECTED, EXIT_USAGEERROR6class TestGeneralUsage:7 def test_config_error(self, testdir):8 testdir.makeconftest("""9 def pytest_configure(config):10 import pytest11 raise pytest.UsageError("hello")12 """)13 result = testdir.runpytest(testdir.tmpdir)14 assert result.ret != 015 result.stderr.fnmatch_lines([16 '*ERROR: hello'17 ])18 def test_root_conftest_syntax_error(self, testdir):19 testdir.makepyfile(conftest="raise SyntaxError\n")20 result = testdir.runpytest()21 result.stderr.fnmatch_lines(["*raise SyntaxError*"])22 assert result.ret != 023 def test_early_hook_error_issue38_1(self, testdir):24 testdir.makeconftest("""25 def pytest_sessionstart():26 0 / 027 """)28 result = testdir.runpytest(testdir.tmpdir)29 assert result.ret != 030 # tracestyle is native by default for hook failures31 result.stdout.fnmatch_lines([32 '*INTERNALERROR*File*conftest.py*line 2*',33 '*0 / 0*',34 ])35 result = testdir.runpytest(testdir.tmpdir, "--fulltrace")36 assert result.ret != 037 # tracestyle is native by default for hook failures38 result.stdout.fnmatch_lines([39 '*INTERNALERROR*def pytest_sessionstart():*',40 '*INTERNALERROR*0 / 0*',41 ])42 def test_early_hook_configure_error_issue38(self, testdir):43 testdir.makeconftest("""44 def pytest_configure():45 0 / 046 """)47 result = testdir.runpytest(testdir.tmpdir)48 assert result.ret != 049 # here we get it on stderr50 result.stderr.fnmatch_lines([51 '*INTERNALERROR*File*conftest.py*line 2*',52 '*0 / 0*',53 ])54 def test_file_not_found(self, testdir):55 result = testdir.runpytest("asd")56 assert result.ret != 057 result.stderr.fnmatch_lines(["ERROR: file not found*asd"])58 def test_file_not_found_unconfigure_issue143(self, testdir):59 testdir.makeconftest("""60 def pytest_configure():61 print("---configure")62 def pytest_unconfigure():63 print("---unconfigure")64 """)65 result = testdir.runpytest("-s", "asd")66 assert result.ret == 4 # EXIT_USAGEERROR67 result.stderr.fnmatch_lines(["ERROR: file not found*asd"])68 result.stdout.fnmatch_lines([69 "*---configure",70 "*---unconfigure",71 ])72 def test_config_preparse_plugin_option(self, testdir):73 testdir.makepyfile(pytest_xyz="""74 def pytest_addoption(parser):75 parser.addoption("--xyz", dest="xyz", action="store")76 """)77 testdir.makepyfile(test_one="""78 def test_option(pytestconfig):79 assert pytestconfig.option.xyz == "123"80 """)81 result = testdir.runpytest("-p", "pytest_xyz", "--xyz=123", syspathinsert=True)82 assert result.ret == 083 result.stdout.fnmatch_lines([84 '*1 passed*',85 ])86 def test_assertion_magic(self, testdir):87 p = testdir.makepyfile("""88 def test_this():89 x = 090 assert x91 """)92 result = testdir.runpytest(p)93 result.stdout.fnmatch_lines([94 "> assert x",95 "E assert 0",96 ])97 assert result.ret == 198 def test_nested_import_error(self, testdir):99 p = testdir.makepyfile("""100 import import_fails101 def test_this():102 assert import_fails.a == 1103 """)104 testdir.makepyfile(import_fails="import does_not_work")105 result = testdir.runpytest(p)106 result.stdout.fnmatch_lines([107 #XXX on jython this fails: "> import import_fails",108 "E ImportError: No module named *does_not_work*",109 ])110 assert result.ret == 1111 def test_not_collectable_arguments(self, testdir):112 p1 = testdir.makepyfile("")113 p2 = testdir.makefile(".pyc", "123")114 result = testdir.runpytest(p1, p2)115 assert result.ret116 result.stderr.fnmatch_lines([117 "*ERROR: not found:*%s" %(p2.basename,)118 ])119 def test_issue486_better_reporting_on_conftest_load_failure(self, testdir):120 testdir.makepyfile("")121 testdir.makeconftest("import qwerty")122 result = testdir.runpytest("--help")123 result.stdout.fnmatch_lines("""124 *--version*125 *warning*conftest.py*126 """)127 result = testdir.runpytest()128 result.stderr.fnmatch_lines("""129 *ERROR*could not load*conftest.py*130 """)131 def test_early_skip(self, testdir):132 testdir.mkdir("xyz")133 testdir.makeconftest("""134 import pytest135 def pytest_collect_directory():136 pytest.skip("early")137 """)138 result = testdir.runpytest()139 assert result.ret == EXIT_NOTESTSCOLLECTED140 result.stdout.fnmatch_lines([141 "*1 skip*"142 ])143 def test_issue88_initial_file_multinodes(self, testdir):144 testdir.makeconftest("""145 import pytest146 class MyFile(pytest.File):147 def collect(self):148 return [MyItem("hello", parent=self)]149 def pytest_collect_file(path, parent):150 return MyFile(path, parent)151 class MyItem(pytest.Item):152 pass153 """)154 p = testdir.makepyfile("def test_hello(): pass")155 result = testdir.runpytest(p, "--collect-only")156 result.stdout.fnmatch_lines([157 "*MyFile*test_issue88*",158 "*Module*test_issue88*",159 ])160 def test_issue93_initialnode_importing_capturing(self, testdir):161 testdir.makeconftest("""162 import sys163 print ("should not be seen")164 sys.stderr.write("stder42\\n")165 """)166 result = testdir.runpytest()167 assert result.ret == EXIT_NOTESTSCOLLECTED168 assert "should not be seen" not in result.stdout.str()169 assert "stderr42" not in result.stderr.str()170 def test_conftest_printing_shows_if_error(self, testdir):171 testdir.makeconftest("""172 print ("should be seen")173 assert 0174 """)175 result = testdir.runpytest()176 assert result.ret != 0177 assert "should be seen" in result.stdout.str()178 @pytest.mark.skipif(not hasattr(py.path.local, 'mksymlinkto'),179 reason="symlink not available on this platform")180 def test_chdir(self, testdir):181 testdir.tmpdir.join("py").mksymlinkto(py._pydir)182 p = testdir.tmpdir.join("main.py")183 p.write(_pytest._code.Source("""184 import sys, os185 sys.path.insert(0, '')186 import py187 print (py.__file__)188 print (py.__path__)189 os.chdir(os.path.dirname(os.getcwd()))190 print (py.log)191 """))192 result = testdir.runpython(p)193 assert not result.ret194 def test_issue109_sibling_conftests_not_loaded(self, testdir):195 sub1 = testdir.tmpdir.mkdir("sub1")196 sub2 = testdir.tmpdir.mkdir("sub2")197 sub1.join("conftest.py").write("assert 0")198 result = testdir.runpytest(sub2)199 assert result.ret == EXIT_NOTESTSCOLLECTED200 sub2.ensure("__init__.py")201 p = sub2.ensure("test_hello.py")202 result = testdir.runpytest(p)203 assert result.ret == EXIT_NOTESTSCOLLECTED204 result = testdir.runpytest(sub1)205 assert result.ret == EXIT_USAGEERROR206 def test_directory_skipped(self, testdir):207 testdir.makeconftest("""208 import pytest209 def pytest_ignore_collect():210 pytest.skip("intentional")211 """)212 testdir.makepyfile("def test_hello(): pass")213 result = testdir.runpytest()214 assert result.ret == EXIT_NOTESTSCOLLECTED215 result.stdout.fnmatch_lines([216 "*1 skipped*"217 ])218 def test_multiple_items_per_collector_byid(self, testdir):219 c = testdir.makeconftest("""220 import pytest221 class MyItem(pytest.Item):222 def runtest(self):223 pass224 class MyCollector(pytest.File):225 def collect(self):226 return [MyItem(name="xyz", parent=self)]227 def pytest_collect_file(path, parent):228 if path.basename.startswith("conftest"):229 return MyCollector(path, parent)230 """)231 result = testdir.runpytest(c.basename+"::"+"xyz")232 assert result.ret == 0233 result.stdout.fnmatch_lines([234 "*1 pass*",235 ])236 def test_skip_on_generated_funcarg_id(self, testdir):237 testdir.makeconftest("""238 import pytest239 def pytest_generate_tests(metafunc):240 metafunc.addcall({'x': 3}, id='hello-123')241 def pytest_runtest_setup(item):242 print (item.keywords)243 if 'hello-123' in item.keywords:244 pytest.skip("hello")245 assert 0246 """)247 p = testdir.makepyfile("""def test_func(x): pass""")248 res = testdir.runpytest(p)249 assert res.ret == 0250 res.stdout.fnmatch_lines(["*1 skipped*"])251 def test_direct_addressing_selects(self, testdir):252 p = testdir.makepyfile("""253 def pytest_generate_tests(metafunc):254 metafunc.addcall({'i': 1}, id="1")255 metafunc.addcall({'i': 2}, id="2")256 def test_func(i):257 pass258 """)259 res = testdir.runpytest(p.basename + "::" + "test_func[1]")260 assert res.ret == 0261 res.stdout.fnmatch_lines(["*1 passed*"])262 def test_direct_addressing_notfound(self, testdir):263 p = testdir.makepyfile("""264 def test_func():265 pass266 """)267 res = testdir.runpytest(p.basename + "::" + "test_notfound")268 assert res.ret269 res.stderr.fnmatch_lines(["*ERROR*not found*"])270 def test_docstring_on_hookspec(self):271 from _pytest import hookspec272 for name, value in vars(hookspec).items():273 if name.startswith("pytest_"):274 assert value.__doc__, "no docstring for %s" % name275 def test_initialization_error_issue49(self, testdir):276 testdir.makeconftest("""277 def pytest_configure():278 x279 """)280 result = testdir.runpytest()281 assert result.ret == 3 # internal error282 result.stderr.fnmatch_lines([283 "INTERNAL*pytest_configure*",284 "INTERNAL*x*",285 ])286 assert 'sessionstarttime' not in result.stderr.str()287 @pytest.mark.parametrize('lookfor', ['test_fun.py', 'test_fun.py::test_a'])288 def test_issue134_report_syntaxerror_when_collecting_member(self, testdir, lookfor):289 testdir.makepyfile(test_fun="""290 def test_a():291 pass292 def""")293 result = testdir.runpytest(lookfor)294 result.stdout.fnmatch_lines(['*SyntaxError*'])295 if '::' in lookfor:296 result.stderr.fnmatch_lines([297 '*ERROR*',298 ])299 assert result.ret == 4 # usage error only if item not found300 def test_report_all_failed_collections_initargs(self, testdir):301 testdir.makepyfile(test_a="def", test_b="def")302 result = testdir.runpytest("test_a.py::a", "test_b.py::b")303 result.stderr.fnmatch_lines([304 "*ERROR*test_a.py::a*",305 "*ERROR*test_b.py::b*",306 ])307 def test_namespace_import_doesnt_confuse_import_hook(self, testdir):308 # Ref #383. Python 3.3's namespace package messed with our import hooks309 # Importing a module that didn't exist, even if the ImportError was310 # gracefully handled, would make our test crash.311 testdir.mkdir('not_a_package')312 p = testdir.makepyfile("""313 try:314 from not_a_package import doesnt_exist315 except ImportError:316 # We handle the import error gracefully here317 pass318 def test_whatever():319 pass320 """)321 res = testdir.runpytest(p.basename)322 assert res.ret == 0323 def test_unknown_option(self, testdir):324 result = testdir.runpytest("--qwlkej")325 result.stderr.fnmatch_lines("""326 *unrecognized*327 """)328 def test_getsourcelines_error_issue553(self, testdir, monkeypatch):329 monkeypatch.setattr("inspect.getsourcelines", None)330 p = testdir.makepyfile("""331 def raise_error(obj):332 raise IOError('source code not available')333 import inspect334 inspect.getsourcelines = raise_error335 def test_foo(invalid_fixture):336 pass337 """)338 res = testdir.runpytest(p)339 res.stdout.fnmatch_lines([340 "*source code not available*",341 "*fixture 'invalid_fixture' not found",342 ])343 def test_plugins_given_as_strings(self, tmpdir, monkeypatch):344 """test that str values passed to main() as `plugins` arg345 are interpreted as module names to be imported and registered.346 #855.347 """348 with pytest.raises(ImportError) as excinfo:349 pytest.main([str(tmpdir)], plugins=['invalid.module'])350 assert 'invalid' in str(excinfo.value)351 p = tmpdir.join('test_test_plugins_given_as_strings.py')352 p.write('def test_foo(): pass')353 mod = py.std.types.ModuleType("myplugin")354 monkeypatch.setitem(sys.modules, 'myplugin', mod)355 assert pytest.main(args=[str(tmpdir)], plugins=['myplugin']) == 0356 def test_parameterized_with_bytes_regex(self, testdir):357 p = testdir.makepyfile("""358 import re359 import pytest360 @pytest.mark.parametrize('r', [re.compile(b'foo')])361 def test_stuff(r):362 pass363 """364 )365 res = testdir.runpytest(p)366 res.stdout.fnmatch_lines([367 '*1 passed*'368 ])369class TestInvocationVariants:370 def test_earlyinit(self, testdir):371 p = testdir.makepyfile("""372 import pytest373 assert hasattr(pytest, 'mark')374 """)375 result = testdir.runpython(p)376 assert result.ret == 0377 @pytest.mark.xfail("sys.platform.startswith('java')")378 def test_pydoc(self, testdir):379 for name in ('py.test', 'pytest'):380 result = testdir.runpython_c("import %s;help(%s)" % (name, name))381 assert result.ret == 0382 s = result.stdout.str()383 assert 'MarkGenerator' in s384 def test_import_star_py_dot_test(self, testdir):385 p = testdir.makepyfile("""386 from py.test import *387 #collect388 #cmdline389 #Item390 #assert collect.Item is Item391 #assert collect.Collector is Collector392 main393 skip394 xfail395 """)396 result = testdir.runpython(p)397 assert result.ret == 0398 def test_import_star_pytest(self, testdir):399 p = testdir.makepyfile("""400 from pytest import *401 #Item402 #File403 main404 skip405 xfail406 """)407 result = testdir.runpython(p)408 assert result.ret == 0409 def test_double_pytestcmdline(self, testdir):410 p = testdir.makepyfile(run="""411 import pytest412 pytest.main()413 pytest.main()414 """)415 testdir.makepyfile("""416 def test_hello():417 pass418 """)419 result = testdir.runpython(p)420 result.stdout.fnmatch_lines([421 "*1 passed*",422 "*1 passed*",423 ])424 def test_python_minus_m_invocation_ok(self, testdir):425 p1 = testdir.makepyfile("def test_hello(): pass")426 res = testdir.run(py.std.sys.executable, "-m", "pytest", str(p1))427 assert res.ret == 0428 def test_python_minus_m_invocation_fail(self, testdir):429 p1 = testdir.makepyfile("def test_fail(): 0/0")430 res = testdir.run(py.std.sys.executable, "-m", "pytest", str(p1))431 assert res.ret == 1432 def test_python_pytest_package(self, testdir):433 p1 = testdir.makepyfile("def test_pass(): pass")434 res = testdir.run(py.std.sys.executable, "-m", "pytest", str(p1))435 assert res.ret == 0436 res.stdout.fnmatch_lines(["*1 passed*"])437 def test_equivalence_pytest_pytest(self):438 assert pytest.main == py.test.cmdline.main439 def test_invoke_with_string(self, capsys):440 retcode = pytest.main("-h")441 assert not retcode442 out, err = capsys.readouterr()443 assert "--help" in out444 pytest.raises(ValueError, lambda: pytest.main(0))445 def test_invoke_with_path(self, tmpdir, capsys):446 retcode = pytest.main(tmpdir)447 assert retcode == EXIT_NOTESTSCOLLECTED448 out, err = capsys.readouterr()449 def test_invoke_plugin_api(self, testdir, capsys):450 class MyPlugin:451 def pytest_addoption(self, parser):452 parser.addoption("--myopt")453 pytest.main(["-h"], plugins=[MyPlugin()])454 out, err = capsys.readouterr()455 assert "--myopt" in out456 def test_pyargs_importerror(self, testdir, monkeypatch):457 monkeypatch.delenv('PYTHONDONTWRITEBYTECODE', False)458 path = testdir.mkpydir("tpkg")459 path.join("test_hello.py").write('raise ImportError')460 result = testdir.runpytest("--pyargs", "tpkg.test_hello")461 assert result.ret != 0462 # FIXME: It would be more natural to match NOT463 # "ERROR*file*or*package*not*found*".464 result.stdout.fnmatch_lines([465 "*collected 0 items*"466 ])467 def test_cmdline_python_package(self, testdir, monkeypatch):468 monkeypatch.delenv('PYTHONDONTWRITEBYTECODE', False)469 path = testdir.mkpydir("tpkg")470 path.join("test_hello.py").write("def test_hello(): pass")471 path.join("test_world.py").write("def test_world(): pass")472 result = testdir.runpytest("--pyargs", "tpkg")473 assert result.ret == 0474 result.stdout.fnmatch_lines([475 "*2 passed*"476 ])477 result = testdir.runpytest("--pyargs", "tpkg.test_hello")478 assert result.ret == 0479 result.stdout.fnmatch_lines([480 "*1 passed*"481 ])482 def join_pythonpath(what):483 cur = py.std.os.environ.get('PYTHONPATH')484 if cur:485 return str(what) + ':' + cur486 return what487 empty_package = testdir.mkpydir("empty_package")488 monkeypatch.setenv('PYTHONPATH', join_pythonpath(empty_package))489 result = testdir.runpytest("--pyargs", ".")490 assert result.ret == 0491 result.stdout.fnmatch_lines([492 "*2 passed*"493 ])494 monkeypatch.setenv('PYTHONPATH', join_pythonpath(testdir))495 path.join('test_hello.py').remove()496 result = testdir.runpytest("--pyargs", "tpkg.test_hello")497 assert result.ret != 0498 result.stderr.fnmatch_lines([499 "*not*found*test_hello*",500 ])501 def test_cmdline_python_package_not_exists(self, testdir):502 result = testdir.runpytest("--pyargs", "tpkgwhatv")503 assert result.ret504 result.stderr.fnmatch_lines([505 "ERROR*file*or*package*not*found*",506 ])507 @pytest.mark.xfail(reason="decide: feature or bug")508 def test_noclass_discovery_if_not_testcase(self, testdir):509 testpath = testdir.makepyfile("""510 import unittest511 class TestHello(object):512 def test_hello(self):513 assert self.attr514 class RealTest(unittest.TestCase, TestHello):515 attr = 42516 """)517 reprec = testdir.inline_run(testpath)518 reprec.assertoutcome(passed=1)519 def test_doctest_id(self, testdir):520 testdir.makefile('.txt', """521 >>> x=3522 >>> x523 4524 """)525 result = testdir.runpytest("-rf")526 lines = result.stdout.str().splitlines()527 for line in lines:528 if line.startswith("FAIL "):529 testid = line[5:].strip()530 break531 result = testdir.runpytest(testid, '-rf')532 result.stdout.fnmatch_lines([533 line,534 "*1 failed*",535 ])536 def test_core_backward_compatibility(self):537 """Test backward compatibility for get_plugin_manager function. See #787."""538 import _pytest.config539 assert type(_pytest.config.get_plugin_manager()) is _pytest.config.PytestPluginManager540 def test_has_plugin(self, request):541 """Test hasplugin function of the plugin manager (#932)."""542 assert request.config.pluginmanager.hasplugin('python')543class TestDurations:544 source = """545 import time546 frag = 0.002547 def test_something():548 pass549 def test_2():550 time.sleep(frag*5)551 def test_1():552 time.sleep(frag)553 def test_3():554 time.sleep(frag*10)555 """556 def test_calls(self, testdir):557 testdir.makepyfile(self.source)558 result = testdir.runpytest("--durations=10")559 assert result.ret == 0560 result.stdout.fnmatch_lines_random([561 "*durations*",562 "*call*test_3*",563 "*call*test_2*",564 "*call*test_1*",565 ])566 def test_calls_show_2(self, testdir):567 testdir.makepyfile(self.source)568 result = testdir.runpytest("--durations=2")569 assert result.ret == 0570 lines = result.stdout.get_lines_after("*slowest*durations*")571 assert "4 passed" in lines[2]572 def test_calls_showall(self, testdir):573 testdir.makepyfile(self.source)574 result = testdir.runpytest("--durations=0")575 assert result.ret == 0576 for x in "123":577 for y in 'call',: #'setup', 'call', 'teardown':578 for line in result.stdout.lines:579 if ("test_%s" % x) in line and y in line:580 break581 else:582 raise AssertionError("not found %s %s" % (x,y))583 def test_with_deselected(self, testdir):584 testdir.makepyfile(self.source)585 result = testdir.runpytest("--durations=2", "-k test_1")586 assert result.ret == 0587 result.stdout.fnmatch_lines([588 "*durations*",589 "*call*test_1*",590 ])591 def test_with_failing_collection(self, testdir):592 testdir.makepyfile(self.source)593 testdir.makepyfile(test_collecterror="""xyz""")594 result = testdir.runpytest("--durations=2", "-k test_1")595 assert result.ret != 0596 result.stdout.fnmatch_lines([597 "*durations*",598 "*call*test_1*",599 ])600class TestDurationWithFixture:601 source = """602 import time603 frag = 0.001604 def setup_function(func):605 time.sleep(frag * 3)606 def test_1():607 time.sleep(frag*2)608 def test_2():609 time.sleep(frag)610 """611 def test_setup_function(self, testdir):612 testdir.makepyfile(self.source)613 result = testdir.runpytest("--durations=10")614 assert result.ret == 0615 result.stdout.fnmatch_lines_random("""616 *durations*617 * setup *test_1*618 * call *test_1*...

Full Screen

Full Screen

test_doctest.py

Source:test_doctest.py Github

copy

Full Screen

1# encoding: utf-82import sys3import _pytest._code4from _pytest.doctest import DoctestItem, DoctestModule, DoctestTextfile5import pytest6class TestDoctests:7 def test_collect_testtextfile(self, testdir):8 w = testdir.maketxtfile(whatever="")9 checkfile = testdir.maketxtfile(test_something="""10 alskdjalsdk11 >>> i = 512 >>> i-113 414 """)15 for x in (testdir.tmpdir, checkfile):16 #print "checking that %s returns custom items" % (x,)17 items, reprec = testdir.inline_genitems(x)18 assert len(items) == 119 assert isinstance(items[0], DoctestTextfile)20 items, reprec = testdir.inline_genitems(w)21 assert len(items) == 122 def test_collect_module_empty(self, testdir):23 path = testdir.makepyfile(whatever="#")24 for p in (path, testdir.tmpdir):25 items, reprec = testdir.inline_genitems(p,26 '--doctest-modules')27 assert len(items) == 028 def test_collect_module_single_modulelevel_doctest(self, testdir):29 path = testdir.makepyfile(whatever='""">>> pass"""')30 for p in (path, testdir.tmpdir):31 items, reprec = testdir.inline_genitems(p,32 '--doctest-modules')33 assert len(items) == 134 assert isinstance(items[0], DoctestItem)35 assert isinstance(items[0].parent, DoctestModule)36 def test_collect_module_two_doctest_one_modulelevel(self, testdir):37 path = testdir.makepyfile(whatever="""38 '>>> x = None'39 def my_func():40 ">>> magic = 42 "41 """)42 for p in (path, testdir.tmpdir):43 items, reprec = testdir.inline_genitems(p,44 '--doctest-modules')45 assert len(items) == 246 assert isinstance(items[0], DoctestItem)47 assert isinstance(items[1], DoctestItem)48 assert isinstance(items[0].parent, DoctestModule)49 assert items[0].parent is items[1].parent50 def test_collect_module_two_doctest_no_modulelevel(self, testdir):51 path = testdir.makepyfile(whatever="""52 '# Empty'53 def my_func():54 ">>> magic = 42 "55 def unuseful():56 '''57 # This is a function58 # >>> # it doesn't have any doctest59 '''60 def another():61 '''62 # This is another function63 >>> import os # this one does have a doctest64 '''65 """)66 for p in (path, testdir.tmpdir):67 items, reprec = testdir.inline_genitems(p,68 '--doctest-modules')69 assert len(items) == 270 assert isinstance(items[0], DoctestItem)71 assert isinstance(items[1], DoctestItem)72 assert isinstance(items[0].parent, DoctestModule)73 assert items[0].parent is items[1].parent74 def test_simple_doctestfile(self, testdir):75 p = testdir.maketxtfile(test_doc="""76 >>> x = 177 >>> x == 178 False79 """)80 reprec = testdir.inline_run(p, )81 reprec.assertoutcome(failed=1)82 def test_new_pattern(self, testdir):83 p = testdir.maketxtfile(xdoc="""84 >>> x = 185 >>> x == 186 False87 """)88 reprec = testdir.inline_run(p, "--doctest-glob=x*.txt")89 reprec.assertoutcome(failed=1)90 def test_multiple_patterns(self, testdir):91 """Test support for multiple --doctest-glob arguments (#1255).92 """93 testdir.maketxtfile(xdoc="""94 >>> 195 196 """)97 testdir.makefile('.foo', test="""98 >>> 199 1100 """)101 testdir.maketxtfile(test_normal="""102 >>> 1103 1104 """)105 expected = set(['xdoc.txt', 'test.foo', 'test_normal.txt'])106 assert set(x.basename for x in testdir.tmpdir.listdir()) == expected107 args = ["--doctest-glob=xdoc*.txt", "--doctest-glob=*.foo"]108 result = testdir.runpytest(*args)109 result.stdout.fnmatch_lines([110 '*test.foo *',111 '*xdoc.txt *',112 '*2 passed*',113 ])114 result = testdir.runpytest()115 result.stdout.fnmatch_lines([116 '*test_normal.txt *',117 '*1 passed*',118 ])119 def test_doctest_unexpected_exception(self, testdir):120 testdir.maketxtfile("""121 >>> i = 0122 >>> 0 / i123 2124 """)125 result = testdir.runpytest("--doctest-modules")126 result.stdout.fnmatch_lines([127 "*unexpected_exception*",128 "*>>> i = 0*",129 "*>>> 0 / i*",130 "*UNEXPECTED*ZeroDivision*",131 ])132 def test_docstring_context_around_error(self, testdir):133 """Test that we show some context before the actual line of a failing134 doctest.135 """136 testdir.makepyfile('''137 def foo():138 """139 text-line-1140 text-line-2141 text-line-3142 text-line-4143 text-line-5144 text-line-6145 text-line-7146 text-line-8147 text-line-9148 text-line-10149 text-line-11150 >>> 1 + 1151 3152 text-line-after153 """154 ''')155 result = testdir.runpytest('--doctest-modules')156 result.stdout.fnmatch_lines([157 '*docstring_context_around_error*',158 '005*text-line-3',159 '006*text-line-4',160 '013*text-line-11',161 '014*>>> 1 + 1',162 'Expected:',163 ' 3',164 'Got:',165 ' 2',166 ])167 # lines below should be trimmed out168 assert 'text-line-2' not in result.stdout.str()169 assert 'text-line-after' not in result.stdout.str()170 def test_doctest_linedata_missing(self, testdir):171 testdir.tmpdir.join('hello.py').write(_pytest._code.Source("""172 class Fun(object):173 @property174 def test(self):175 '''176 >>> a = 1177 >>> 1/0178 '''179 """))180 result = testdir.runpytest("--doctest-modules")181 result.stdout.fnmatch_lines([182 "*hello*",183 "*EXAMPLE LOCATION UNKNOWN, not showing all tests of that example*",184 "*1/0*",185 "*UNEXPECTED*ZeroDivision*",186 "*1 failed*",187 ])188 def test_doctest_unex_importerror(self, testdir):189 testdir.tmpdir.join("hello.py").write(_pytest._code.Source("""190 import asdalsdkjaslkdjasd191 """))192 testdir.maketxtfile("""193 >>> import hello194 >>>195 """)196 result = testdir.runpytest("--doctest-modules")197 result.stdout.fnmatch_lines([198 "*>>> import hello",199 "*UNEXPECTED*ImportError*",200 "*import asdals*",201 ])202 def test_doctestmodule(self, testdir):203 p = testdir.makepyfile("""204 '''205 >>> x = 1206 >>> x == 1207 False208 '''209 """)210 reprec = testdir.inline_run(p, "--doctest-modules")211 reprec.assertoutcome(failed=1)212 def test_doctestmodule_external_and_issue116(self, testdir):213 p = testdir.mkpydir("hello")214 p.join("__init__.py").write(_pytest._code.Source("""215 def somefunc():216 '''217 >>> i = 0218 >>> i + 1219 2220 '''221 """))222 result = testdir.runpytest(p, "--doctest-modules")223 result.stdout.fnmatch_lines([224 '004 *>>> i = 0',225 '005 *>>> i + 1',226 '*Expected:',227 "* 2",228 "*Got:",229 "* 1",230 "*:5: DocTestFailure"231 ])232 def test_txtfile_failing(self, testdir):233 p = testdir.maketxtfile("""234 >>> i = 0235 >>> i + 1236 2237 """)238 result = testdir.runpytest(p, "-s")239 result.stdout.fnmatch_lines([240 '001 >>> i = 0',241 '002 >>> i + 1',242 'Expected:',243 " 2",244 "Got:",245 " 1",246 "*test_txtfile_failing.txt:2: DocTestFailure"247 ])248 def test_txtfile_with_fixtures(self, testdir):249 p = testdir.maketxtfile("""250 >>> dir = getfixture('tmpdir')251 >>> type(dir).__name__252 'LocalPath'253 """)254 reprec = testdir.inline_run(p, )255 reprec.assertoutcome(passed=1)256 def test_txtfile_with_usefixtures_in_ini(self, testdir):257 testdir.makeini("""258 [pytest]259 usefixtures = myfixture260 """)261 testdir.makeconftest("""262 import pytest263 @pytest.fixture264 def myfixture(monkeypatch):265 monkeypatch.setenv("HELLO", "WORLD")266 """)267 p = testdir.maketxtfile("""268 >>> import os269 >>> os.environ["HELLO"]270 'WORLD'271 """)272 reprec = testdir.inline_run(p, )273 reprec.assertoutcome(passed=1)274 def test_doctestmodule_with_fixtures(self, testdir):275 p = testdir.makepyfile("""276 '''277 >>> dir = getfixture('tmpdir')278 >>> type(dir).__name__279 'LocalPath'280 '''281 """)282 reprec = testdir.inline_run(p, "--doctest-modules")283 reprec.assertoutcome(passed=1)284 def test_doctestmodule_three_tests(self, testdir):285 p = testdir.makepyfile("""286 '''287 >>> dir = getfixture('tmpdir')288 >>> type(dir).__name__289 'LocalPath'290 '''291 def my_func():292 '''293 >>> magic = 42294 >>> magic - 42295 0296 '''297 def unuseful():298 pass299 def another():300 '''301 >>> import os302 >>> os is os303 True304 '''305 """)306 reprec = testdir.inline_run(p, "--doctest-modules")307 reprec.assertoutcome(passed=3)308 def test_doctestmodule_two_tests_one_fail(self, testdir):309 p = testdir.makepyfile("""310 class MyClass:311 def bad_meth(self):312 '''313 >>> magic = 42314 >>> magic315 0316 '''317 def nice_meth(self):318 '''319 >>> magic = 42320 >>> magic - 42321 0322 '''323 """)324 reprec = testdir.inline_run(p, "--doctest-modules")325 reprec.assertoutcome(failed=1, passed=1)326 def test_ignored_whitespace(self, testdir):327 testdir.makeini("""328 [pytest]329 doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE330 """)331 p = testdir.makepyfile("""332 class MyClass:333 '''334 >>> a = "foo "335 >>> print(a)336 foo337 '''338 pass339 """)340 reprec = testdir.inline_run(p, "--doctest-modules")341 reprec.assertoutcome(passed=1)342 def test_non_ignored_whitespace(self, testdir):343 testdir.makeini("""344 [pytest]345 doctest_optionflags = ELLIPSIS346 """)347 p = testdir.makepyfile("""348 class MyClass:349 '''350 >>> a = "foo "351 >>> print(a)352 foo353 '''354 pass355 """)356 reprec = testdir.inline_run(p, "--doctest-modules")357 reprec.assertoutcome(failed=1, passed=0)358 def test_ignored_whitespace_glob(self, testdir):359 testdir.makeini("""360 [pytest]361 doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE362 """)363 p = testdir.maketxtfile(xdoc="""364 >>> a = "foo "365 >>> print(a)366 foo367 """)368 reprec = testdir.inline_run(p, "--doctest-glob=x*.txt")369 reprec.assertoutcome(passed=1)370 def test_non_ignored_whitespace_glob(self, testdir):371 testdir.makeini("""372 [pytest]373 doctest_optionflags = ELLIPSIS374 """)375 p = testdir.maketxtfile(xdoc="""376 >>> a = "foo "377 >>> print(a)378 foo379 """)380 reprec = testdir.inline_run(p, "--doctest-glob=x*.txt")381 reprec.assertoutcome(failed=1, passed=0)382 def test_contains_unicode(self, testdir):383 """Fix internal error with docstrings containing non-ascii characters.384 """385 testdir.makepyfile(u'''386 # encoding: utf-8387 def foo():388 """389 >>> name = 'с' # not letter 'c' but instead Cyrillic 's'.390 'anything'391 """392 ''')393 result = testdir.runpytest('--doctest-modules')394 result.stdout.fnmatch_lines([395 'Got nothing',396 '* 1 failed in*',397 ])398 def test_ignore_import_errors_on_doctest(self, testdir):399 p = testdir.makepyfile("""400 import asdf401 def add_one(x):402 '''403 >>> add_one(1)404 2405 '''406 return x + 1407 """)408 reprec = testdir.inline_run(p, "--doctest-modules",409 "--doctest-ignore-import-errors")410 reprec.assertoutcome(skipped=1, failed=1, passed=0)411 def test_junit_report_for_doctest(self, testdir):412 """413 #713: Fix --junit-xml option when used with --doctest-modules.414 """415 p = testdir.makepyfile("""416 def foo():417 '''418 >>> 1 + 1419 3420 '''421 pass422 """)423 reprec = testdir.inline_run(p, "--doctest-modules",424 "--junit-xml=junit.xml")425 reprec.assertoutcome(failed=1)426class TestLiterals:427 @pytest.mark.parametrize('config_mode', ['ini', 'comment'])428 def test_allow_unicode(self, testdir, config_mode):429 """Test that doctests which output unicode work in all python versions430 tested by pytest when the ALLOW_UNICODE option is used (either in431 the ini file or by an inline comment).432 """433 if config_mode == 'ini':434 testdir.makeini('''435 [pytest]436 doctest_optionflags = ALLOW_UNICODE437 ''')438 comment = ''439 else:440 comment = '#doctest: +ALLOW_UNICODE'441 testdir.maketxtfile(test_doc="""442 >>> b'12'.decode('ascii') {comment}443 '12'444 """.format(comment=comment))445 testdir.makepyfile(foo="""446 def foo():447 '''448 >>> b'12'.decode('ascii') {comment}449 '12'450 '''451 """.format(comment=comment))452 reprec = testdir.inline_run("--doctest-modules")453 reprec.assertoutcome(passed=2)454 @pytest.mark.parametrize('config_mode', ['ini', 'comment'])455 def test_allow_bytes(self, testdir, config_mode):456 """Test that doctests which output bytes work in all python versions457 tested by pytest when the ALLOW_BYTES option is used (either in458 the ini file or by an inline comment)(#1287).459 """460 if config_mode == 'ini':461 testdir.makeini('''462 [pytest]463 doctest_optionflags = ALLOW_BYTES464 ''')465 comment = ''466 else:467 comment = '#doctest: +ALLOW_BYTES'468 testdir.maketxtfile(test_doc="""469 >>> b'foo' {comment}470 'foo'471 """.format(comment=comment))472 testdir.makepyfile(foo="""473 def foo():474 '''475 >>> b'foo' {comment}476 'foo'477 '''478 """.format(comment=comment))479 reprec = testdir.inline_run("--doctest-modules")480 reprec.assertoutcome(passed=2)481 def test_unicode_string(self, testdir):482 """Test that doctests which output unicode fail in Python 2 when483 the ALLOW_UNICODE option is not used. The same test should pass484 in Python 3.485 """486 testdir.maketxtfile(test_doc="""487 >>> b'12'.decode('ascii')488 '12'489 """)490 reprec = testdir.inline_run()491 passed = int(sys.version_info[0] >= 3)492 reprec.assertoutcome(passed=passed, failed=int(not passed))493 def test_bytes_literal(self, testdir):494 """Test that doctests which output bytes fail in Python 3 when495 the ALLOW_BYTES option is not used. The same test should pass496 in Python 2 (#1287).497 """498 testdir.maketxtfile(test_doc="""499 >>> b'foo'500 'foo'501 """)502 reprec = testdir.inline_run()503 passed = int(sys.version_info[0] == 2)504 reprec.assertoutcome(passed=passed, failed=int(not passed))505class TestDoctestSkips:506 """507 If all examples in a doctest are skipped due to the SKIP option, then508 the tests should be SKIPPED rather than PASSED. (#957)509 """510 @pytest.fixture(params=['text', 'module'])511 def makedoctest(self, testdir, request):512 def makeit(doctest):513 mode = request.param514 if mode == 'text':515 testdir.maketxtfile(doctest)516 else:517 assert mode == 'module'518 testdir.makepyfile('"""\n%s"""' % doctest)519 return makeit520 def test_one_skipped(self, testdir, makedoctest):521 makedoctest("""522 >>> 1 + 1 # doctest: +SKIP523 2524 >>> 2 + 2525 4526 """)527 reprec = testdir.inline_run("--doctest-modules")528 reprec.assertoutcome(passed=1)529 def test_one_skipped_failed(self, testdir, makedoctest):530 makedoctest("""531 >>> 1 + 1 # doctest: +SKIP532 2533 >>> 2 + 2534 200535 """)536 reprec = testdir.inline_run("--doctest-modules")537 reprec.assertoutcome(failed=1)538 def test_all_skipped(self, testdir, makedoctest):539 makedoctest("""540 >>> 1 + 1 # doctest: +SKIP541 2542 >>> 2 + 2 # doctest: +SKIP543 200544 """)545 reprec = testdir.inline_run("--doctest-modules")546 reprec.assertoutcome(skipped=1)547class TestDoctestAutoUseFixtures:548 SCOPES = ['module', 'session', 'class', 'function']549 def test_doctest_module_session_fixture(self, testdir):550 """Test that session fixtures are initialized for doctest modules (#768)551 """552 # session fixture which changes some global data, which will553 # be accessed by doctests in a module554 testdir.makeconftest("""555 import pytest556 import sys557 @pytest.yield_fixture(autouse=True, scope='session')558 def myfixture():559 assert not hasattr(sys, 'pytest_session_data')560 sys.pytest_session_data = 1561 yield562 del sys.pytest_session_data563 """)564 testdir.makepyfile(foo="""565 import sys566 def foo():567 '''568 >>> assert sys.pytest_session_data == 1569 '''570 def bar():571 '''572 >>> assert sys.pytest_session_data == 1573 '''574 """)575 result = testdir.runpytest("--doctest-modules")576 result.stdout.fnmatch_lines('*2 passed*')577 @pytest.mark.parametrize('scope', SCOPES)578 @pytest.mark.parametrize('enable_doctest', [True, False])579 def test_fixture_scopes(self, testdir, scope, enable_doctest):580 """Test that auto-use fixtures work properly with doctest modules.581 See #1057 and #1100.582 """583 testdir.makeconftest('''584 import pytest585 @pytest.fixture(autouse=True, scope="{scope}")586 def auto(request):587 return 99588 '''.format(scope=scope))589 testdir.makepyfile(test_1='''590 def test_foo():591 """592 >>> getfixture('auto') + 1593 100594 """595 def test_bar():596 assert 1597 ''')598 params = ('--doctest-modules',) if enable_doctest else ()599 passes = 3 if enable_doctest else 2600 result = testdir.runpytest(*params)601 result.stdout.fnmatch_lines(['*=== %d passed in *' % passes])602 @pytest.mark.parametrize('scope', SCOPES)603 @pytest.mark.parametrize('autouse', [True, False])604 @pytest.mark.parametrize('use_fixture_in_doctest', [True, False])605 def test_fixture_module_doctest_scopes(self, testdir, scope, autouse,606 use_fixture_in_doctest):607 """Test that auto-use fixtures work properly with doctest files.608 See #1057 and #1100.609 """610 testdir.makeconftest('''611 import pytest612 @pytest.fixture(autouse={autouse}, scope="{scope}")613 def auto(request):614 return 99615 '''.format(scope=scope, autouse=autouse))616 if use_fixture_in_doctest:617 testdir.maketxtfile(test_doc="""618 >>> getfixture('auto')619 99620 """)621 else:622 testdir.maketxtfile(test_doc="""623 >>> 1 + 1624 2625 """)626 result = testdir.runpytest('--doctest-modules')627 assert 'FAILURES' not in str(result.stdout.str())628 result.stdout.fnmatch_lines(['*=== 1 passed in *'])629 @pytest.mark.parametrize('scope', SCOPES)630 def test_auto_use_request_attributes(self, testdir, scope):631 """Check that all attributes of a request in an autouse fixture632 behave as expected when requested for a doctest item.633 """634 testdir.makeconftest('''635 import pytest636 @pytest.fixture(autouse=True, scope="{scope}")637 def auto(request):638 if "{scope}" == 'module':639 assert request.module is None640 if "{scope}" == 'class':641 assert request.cls is None642 if "{scope}" == 'function':643 assert request.function is None644 return 99645 '''.format(scope=scope))646 testdir.maketxtfile(test_doc="""647 >>> 1 + 1648 2649 """)650 result = testdir.runpytest('--doctest-modules')651 assert 'FAILURES' not in str(result.stdout.str())...

Full Screen

Full Screen

recursive-readdir-test.js

Source:recursive-readdir-test.js Github

copy

Full Screen

1/* eslint-env mocha */2var assert = require("assert");3var p = require("path");4var readdir = require("../index");5function getAbsolutePath(file) {6 return p.join(__dirname, file);7}8function getAbsolutePaths(files) {9 return files.map(getAbsolutePath);10}11describe("readdir", function() {12 it("correctly lists all files in nested directories", function(done) {13 var expectedFiles = getAbsolutePaths([14 "/testdir/a/a",15 "/testdir/a/beans",16 "/testdir/b/123",17 "/testdir/b/b/hurp-durp",18 "/testdir/c.txt",19 "/testdir/d.txt"20 ]);21 readdir(p.join(__dirname, "testdir"), function(err, list) {22 assert.ifError(err);23 assert.deepEqual(list.sort(), expectedFiles.sort());24 done();25 });26 });27 it("ignores the files listed in the ignores array", function(done) {28 var notExpectedFiles = getAbsolutePaths([29 "/testdir/d.txt",30 "/testdir/a/beans"31 ]);32 readdir(p.join(__dirname, "testdir"), ["d.txt", "beans"], function(33 err,34 list35 ) {36 assert.ifError(err);37 list.forEach(function(file) {38 assert.equal(39 notExpectedFiles.indexOf(file),40 -1,41 'Failed to ignore file "' + file + '".'42 );43 });44 done();45 });46 });47 it("ignores the directories listed in the ignores array", function(done) {48 var notExpectedFiles = getAbsolutePaths([49 "/testdir/a/a",50 "/testdir/a/beans"51 ]);52 readdir(p.join(__dirname, "testdir"), ["**/testdir/a"], function(53 err,54 list55 ) {56 assert.ifError(err);57 list.forEach(function(file) {58 assert.equal(59 notExpectedFiles.indexOf(file),60 -1,61 'Failed to ignore file "' + file + '".'62 );63 });64 done();65 });66 });67 it("ignores symlinked files and directories listed in the ignores array", function(68 done69 ) {70 var notExpectedFiles = getAbsolutePaths([71 "/testsymlinks/testdir/linkeddir/hi.docx",72 "/testsymlinks/testdir/linkedfile.wmf"73 ]);74 readdir(75 p.join(__dirname, "testsymlinks/testdir"),76 ["linkeddir", "linkedfile.wmf"],77 function(err, list) {78 assert.ifError(err);79 list.forEach(function(file) {80 assert.equal(81 notExpectedFiles.indexOf(file),82 -1,83 'Failed to ignore file "' + file + '".'84 );85 });86 done();87 }88 );89 });90 it("supports ignoring files with just basename globbing", function(done) {91 var notExpectedFiles = getAbsolutePaths([92 "/testdir/d.txt",93 "/testdir/a/beans"94 ]);95 readdir(p.join(__dirname, "testdir"), ["*.txt", "beans"], function(96 err,97 list98 ) {99 assert.ifError(err);100 list.forEach(function(file) {101 assert.equal(102 notExpectedFiles.indexOf(file),103 -1,104 'Failed to ignore file "' + file + '".'105 );106 });107 done();108 });109 });110 it("supports ignoring files with the globstar syntax", function(done) {111 var notExpectedFiles = getAbsolutePaths([112 "/testdir/d.txt",113 "/testdir/a/beans"114 ]);115 var ignores = ["**/*.txt", "**/a/beans"];116 readdir(p.join(__dirname, "testdir"), ignores, function(err, list) {117 assert.ifError(err);118 list.forEach(function(file) {119 assert.equal(120 notExpectedFiles.indexOf(file),121 -1,122 'Failed to ignore file "' + file + '".'123 );124 });125 done();126 });127 });128 context("when there is a function in the ignores array", function() {129 it("passes each file and directory path to the function", function(done) {130 var expectedPaths = getAbsolutePaths([131 "/testdir/a",132 "/testdir/a/a",133 "/testdir/a/beans",134 "/testdir/b",135 "/testdir/b/123",136 "/testdir/b/b",137 "/testdir/b/b/hurp-durp",138 "/testdir/c.txt",139 "/testdir/d.txt"140 ]);141 var paths = [];142 function ignoreFunction(path) {143 paths.push(path);144 return false;145 }146 readdir(p.join(__dirname, "testdir"), [ignoreFunction], function(147 err,148 list149 ) {150 assert.ifError(err);151 assert.deepEqual(paths.sort(), expectedPaths.sort());152 done();153 });154 });155 it("passes the stat object of each file to the function as its second argument", function(156 done157 ) {158 var paths = {};159 function ignoreFunction(path, stats) {160 paths[path] = stats;161 return false;162 }163 readdir(p.join(__dirname, "testdir"), [ignoreFunction], function(164 err,165 list166 ) {167 assert.ifError(err);168 assert(paths[getAbsolutePath("/testdir/a")].isDirectory());169 assert(paths[getAbsolutePath("/testdir/c.txt")].isFile());170 done();171 });172 });173 it("ignores files that the function returns true for", function(done) {174 var ignoredFiles = getAbsolutePaths([175 "/testdir/d.txt",176 "/testdir/a/beans"177 ]);178 function ignoreFunction(path) {179 return ignoredFiles.indexOf(path) != -1;180 }181 readdir(p.join(__dirname, "testdir"), [ignoreFunction], function(182 err,183 list184 ) {185 assert.ifError(err);186 list.forEach(function(file) {187 assert.equal(188 ignoredFiles.indexOf(file),189 -1,190 'Failed to ignore file "' + file + '".'191 );192 });193 done();194 });195 });196 it("does not ignore files that the function returns false for", function(197 done198 ) {199 var notIgnoredFiles = getAbsolutePaths([200 "/testdir/d.txt",201 "/testdir/a/beans"202 ]);203 function ignoreFunction(path) {204 return notIgnoredFiles.indexOf(path) == -1;205 }206 readdir(p.join(__dirname, "testdir"), [ignoreFunction], function(207 err,208 list209 ) {210 assert.ifError(err);211 notIgnoredFiles.forEach(function(file) {212 assert.notEqual(213 notIgnoredFiles.indexOf(file),214 -1,215 'Incorrectly ignored file "' + file + '".'216 );217 });218 done();219 });220 });221 it("ignores directories that the function returns true for", function(222 done223 ) {224 var ignoredDirectory = getAbsolutePath("/testdir/a");225 var ignoredFiles = getAbsolutePaths(["/testdir/a/a", "/testdir/a/beans"]);226 function ignoreFunction(path) {227 return ignoredDirectory == path;228 }229 readdir(p.join(__dirname, "testdir"), [ignoreFunction], function(230 err,231 list232 ) {233 assert.ifError(err);234 list.forEach(function(file) {235 assert.equal(236 ignoredFiles.indexOf(file),237 -1,238 'Failed to ignore file "' + file + '".'239 );240 });241 done();242 });243 });244 it("does not ignore directories that the function returns false for", function(245 done246 ) {247 var ignoredDirectory = getAbsolutePath("/testdir/a");248 var notIgnoredFiles = getAbsolutePaths([249 "/testdir/b/123",250 "/testdir/b/b/hurp-durp"251 ]);252 function ignoreFunction(path) {253 return ignoredDirectory == path;254 }255 readdir(p.join(__dirname, "testdir"), [ignoreFunction], function(256 err,257 list258 ) {259 assert.ifError(err);260 notIgnoredFiles.forEach(function(file) {261 assert.notEqual(262 notIgnoredFiles.indexOf(file),263 -1,264 'Incorrectly ignored file "' + file + '".'265 );266 });267 done();268 });269 });270 it("does not descend into directories that the function returns true for", function(271 done272 ) {273 var ignoredDirectory = getAbsolutePath("/testdir/a");274 var ignoredFiles = getAbsolutePaths(["/testdir/a/a", "/testdir/a/beans"]);275 var paths = [];276 function ignoreFunction(path) {277 paths.push(path);278 return ignoredDirectory == path;279 }280 readdir(p.join(__dirname, "testdir"), [ignoreFunction], function(281 err,282 list283 ) {284 assert.ifError(err);285 paths.forEach(function(file) {286 assert.equal(287 ignoredFiles.indexOf(file),288 -1,289 'Transversed file in ignored directory "' + file + '".'290 );291 });292 done();293 });294 });295 });296 it("works when there are no files to report except ignored files", function(297 done298 ) {299 readdir(p.join(__dirname, "testdirBeta"), ["*"], function(err, list) {300 assert.ifError(err);301 assert.equal(list.length, 0, "expect to report 0 files");302 done();303 });304 });305 it("works when negated ignore list is given", function(done) {306 var expectedFiles = getAbsolutePaths(["/testdirBeta/ignore.txt"]);307 readdir(p.join(__dirname, "testdirBeta"), ["!*.txt"], function(err, list) {308 assert.ifError(err);309 assert.deepEqual(310 list.sort(),311 expectedFiles,312 "Failed to find expected files."313 );314 done();315 });316 });317 it("traverses directory and file symbolic links", function(done) {318 var expectedFiles = getAbsolutePaths([319 "/testsymlinks/testdir/linkeddir/hi.docx",320 "/testsymlinks/testdir/linkedfile.wmf"321 ]);322 readdir(p.join(__dirname, "testsymlinks", "testdir"), function(err, list) {323 assert.ifError(err);324 assert.deepEqual(325 list.sort(),326 expectedFiles,327 "Failed to find expected files."328 );329 done();330 });331 });332 if (!global.Promise) {333 console.log("Native Promise not supported - skipping tests");334 } else {335 it("works with promises", function(done) {336 var expectedFiles = getAbsolutePaths([337 "/testdir/a/a",338 "/testdir/a/beans",339 "/testdir/b/123",340 "/testdir/b/b/hurp-durp",341 "/testdir/c.txt",342 "/testdir/d.txt"343 ]);344 readdir(p.join(__dirname, "testdir"))345 .then(function(list) {346 assert.deepEqual(list.sort(), expectedFiles.sort());347 done();348 })349 .catch(done);350 });351 it("correctly ignores when using promises", function(done) {352 var expectedFiles = getAbsolutePaths([353 "/testdir/a/a",354 "/testdir/a/beans",355 "/testdir/b/123",356 "/testdir/b/b/hurp-durp"357 ]);358 readdir(p.join(__dirname, "testdir"), ["*.txt"])359 .then(function(list) {360 assert.deepEqual(list.sort(), expectedFiles.sort());361 done();362 })363 .catch(done);364 });365 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const storybookRoot = require('storybook-root');2storybookRoot.testDir();3const storybookRoot = require('storybook-root');4storybookRoot.testDir();5const storybookRoot = require('storybook-root');6storybookRoot.testDir();7const storybookRoot = require('storybook-root');8storybookRoot.testDir();9const storybookRoot = require('storybook-root');10storybookRoot.testDir();11const storybookRoot = require('storybook-root');12storybookRoot.testDir();13const storybookRoot = require('storybook-root');14storybookRoot.testDir();15const storybookRoot = require('storybook-root');16storybookRoot.testDir();17const storybookRoot = require('storybook-root');18storybookRoot.testDir();19const storybookRoot = require('storybook-root');20storybookRoot.testDir();

Full Screen

Using AI Code Generation

copy

Full Screen

1const storybookRootDir = require('storybook-root-dir');2console.log(storybookRootDir.testDir());3const storybookRootDir = require('storybook-root-dir');4console.log(storybookRootDir.testDir());5const storybookRootDir = require('storybook-root-dir');6console.log(storybookRootDir.testDir());7const storybookRootDir = require('storybook-root-dir');8console.log(storybookRootDir.testDir());9const storybookRootDir = require('storybook-root-dir');10console.log(storybookRootDir.testDir());11const storybookRootDir = require('storybook-root-dir');12console.log(storybookRootDir.testDir());13const storybookRootDir = require('storybook-root-dir');14console.log(storybookRootDir.testDir());15const storybookRootDir = require('storybook-root-dir');16console.log(storybookRootDir.testDir());17const storybookRootDir = require('storybook-root-dir');18console.log(storybookRootDir.testDir());19const storybookRootDir = require('storybook-root-dir');20console.log(storybookRootDir.testDir());21const storybookRootDir = require('storybook-root-dir');22console.log(storybookRootDir.testDir());23const storybookRootDir = require('storybook-root-dir');24console.log(storybookRootDir.testDir());25const storybookRootDir = require('storybook-root-dir');26console.log(storybookRootDir.testDir());

Full Screen

Using AI Code Generation

copy

Full Screen

1import { testDir } from "storybook-root-decorator";2testDir("test");3testDir("test", "test1");4testDir("test", "test1", "test2");5testDir("test", "test1", "test2", "test3");6testDir("test", "test1", "test2", "test3", "test4");7testDir("test", "test1", "test2", "test3", "test4", "test5");8testDir("test", "test1", "test2", "test3", "test4", "test5", "test6");9testDir("test", "test1", "test2", "test3", "test4", "test5", "test6", "test7");10testDir("test", "test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8");11testDir("test", "test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9");12testDir("test", "test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10");13testDir("test", "test1", "test2", "test3", "test4", "test5", "test6

Full Screen

Using AI Code Generation

copy

Full Screen

1import {testDir} from 'storybook-root'2testDir('testDir')3import {testDir} from 'storybook-root'4testDir('testDir')5import {testDir} from 'storybook-root'6testDir('testDir')7import {testDir} from 'storybook-root'8testDir('testDir')9import {testDir} from 'storybook-root'10testDir('testDir')11import {testDir} from 'storybook-root'12testDir('testDir')13import {testDir} from 'storybook-root'14testDir('testDir')15import {testDir} from 'storybook-root'16testDir('testDir')17import {testDir} from 'storybook-root'18testDir('testDir')19import {testDir} from 'storybook-root'20testDir('testDir')21import {testDir} from 'storybook-root'22testDir('testDir')23import {test

Full Screen

Using AI Code Generation

copy

Full Screen

1const storybookRoot = require('storybook-root')2const root = storybookRoot.testDir(__dirname)3const path = require('path')4const storybook = path.join(root, 'storybook')5console.log(storybook)6const storybookRoot = require('storybook-root')7const root = storybookRoot.testDir(__dirname)8const path = require('path')9const stories = path.join(root, 'stories')10console.log(stories)

Full Screen

Using AI Code Generation

copy

Full Screen

1const testDir = require('storybook-root-dir').testDir;2const path = require('path');3const myTestDir = testDir(path.join('src', 'myTestDir'));4const storybookRootDir = require('storybook-root-dir').storybookRootDir;5const path = require('path');6const myStorybookRootDir = storybookRootDir(path.join('src', 'myStorybookRootDir'));7const storybookRootDir = require('storybook-root-dir').storybookRootDir;8const path = require('path');9const myStorybookRootDir = storybookRootDir(path.join('src', 'myStorybookRootDir'));10const testDir = require('storybook-root-dir').testDir;11const path = require('path');12const myTestDir = testDir(path.join('src', 'myTestDir'));13const storybookRootDir = require('storybook-root-dir').storybookRootDir;14const path = require('path');15const myStorybookRootDir = storybookRootDir(path.join('src', 'myStorybookRootDir'));16const path = require('path');17const testDir = require('storybook-root-dir').testDir;18const myTestDir = testDir(path.join('src', 'myTestDir'));19module.exports = async ({ config, mode }) => {20 config.module.rules.push({21 include: path.resolve(__dirname, myTestDir),22 {23 options: {24 },25 },26 });27 return config;28};29module.exports = {

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful